Function only defined but immediately executed anyway(只定义了函数,但无论如何都会立即执行)
问题描述
我的文件 ajaxrequest.js 中有一段简短的 javascript 代码有问题.这里是:
I'm having trouble with a short javascript code in my file ajaxrequest.js . Here it is :
function afficher () {
$.post('requete_affichage.php', function (data) {
$('#name-data').text(data); });
}
$('#bouton2').on('click', afficher());
所以问题是,只要我在浏览器中点击localhost",该函数就会立即执行并将数据插入到我的 index.html 页面的 div#name-data 字段中,而不是等待我点击#bouton2 这样做.有什么想法吗?
So the problem is the function immediately executes and inserts the data in the div#name-data field of my index.html page as soon as i hit "localhost" in my browser, and doesn't wait for my click on #bouton2 to do so. Any idea ?
推荐答案
通过在函数后面加上方括号,您可以告诉它立即执行.要将函数引用分配给单击处理程序,请删除括号:
By including the brackets after the function you are telling it to execute immediately. To assign the function reference to the click handler, remove the brackets:
$('#bouton2').on('click', afficher);
这篇关于只定义了函数,但无论如何都会立即执行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:只定义了函数,但无论如何都会立即执行


- Mod使用GET变量将子域重写为PHP 2021-01-01
- 带有通配符的 Laravel 验证器 2021-01-01
- PHP Count 布尔数组中真值的数量 2021-01-01
- Laravel 仓库 2022-01-01
- 从 PHP 中的输入表单获取日期 2022-01-01
- 正确分离 PHP 中的逻辑/样式 2021-01-01
- 如何定位 php.ini 文件 (xampp) 2022-01-01
- 没有作曲家的 PSR4 自动加载 2022-01-01
- SoapClient 设置自定义 HTTP Header 2021-01-01
- Oracle 即时客户端 DYLD_LIBRARY_PATH 错误 2022-01-01