只定义了函数,但无论如何都会立即执行 [英] Function only defined but immediately executed anyway

查看:24
本文介绍了只定义了函数,但无论如何都会立即执行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的文件 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆