只定义了函数,但无论如何都会立即执行

2022-01-09 00:00:00 jquery onclick php html

我的文件 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);

相关文章