仅定义函数,但无论如何立即执行 [英] 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);
这篇关于仅定义函数,但无论如何立即执行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文