javascript函数在未被调用的情况下运行

javascript函数在未被调用的情况下运行,javascript,function-calls,Javascript,Function Calls,我想知道为什么页面一加载,就会调用函数btw_bijtellen()。我想通过点击来调用它 var $ = function (id) { return document.getElementById (id); } function btw_bijtellen () { window.alert("we want to calculate something after clicking th button"); } $("bereken").onclick = btw_b

我想知道为什么页面一加载,就会调用函数
btw_bijtellen()
。我想通过点击来调用它

var $ = function (id) {
    return document.getElementById (id);
}

function btw_bijtellen () {
    window.alert("we want to calculate something after clicking th button");
}

$("bereken").onclick = btw_bijtellen ();
您已经添加了导致函数执行的
()

例如:

var myFunc1 = function() {
    alert('Hello');
}(); // <--- () causes self execution

var myFunc2 = function() {
    return 5 + 5;
};

var some_value = myFunc2(); // <--- Again () causes execution (you'd expect this one)
var myFunc1=function(){
警惕(“你好”);
}(); //  在函数名后面加上
()
,就是调用函数名的方式

如果要将
btw_bijtellen
分配给
onclick
,请从问题代码的最后一行删除
()


使用那里的
()
调用函数并将其返回值分配给
onclick
。由于该函数没有
返回语句,因此该值将是未定义的,这不是您想要的。

如果您希望调用函数,请单击“使用”

$("bereken").on('click', btw_bijtellen);
更新(根据WAO的查询) 如果需要传递参数,则需要指定为第二个参数。
$.on()
获取
事件处理程序中的数据

$("bereken").on('click', {key1: value1, key2: value2, keyn: valuen}, btw_bijtellen);
其中,您可以从
event.data

var function = btw_bijtellen(event) {
    var data = event.data;
    console.log(data);

    var key1 = event.data.key1;
    console.log(key1);  // this will output value1
}

请阅读此链接

顺便说一句,对于@bert,这意味着您的onclick处理程序被分配为“未定义”-因为运行此返回“未定义”的函数会将此结果分配给onclick。@Lloyd因此,在声明或调用时,只有括号,其余的(仅叶分配?)没有括号?声明或调用yes。对于赋值,只需删除它们。如果要将参数传递给'btw_bijtellen'函数,该怎么办?