javascript javascript函数在没有被调用的情况下运行
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14829410/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
javascript function running without being called
提问by pwp
I wonder why, as soon as the page loads, the function btw_bijtellen ()
is called. I wanted to call it by clicking...
我想知道为什么一旦页面加载,该函数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 ();
回答by Lloyd
You've added ()
which causes the function to execute.
您已添加()
which 导致函数执行。
For example:
例如:
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)
In your case, as mentioned in comments you're basically telling the onclick
to set its value to the return value of the function.
在您的情况下,如评论中所述,您基本上是在告诉onclick
将其值设置为函数的返回值。
If you drop the ()
it should run as expected.
如果你删除()
它应该按预期运行。
回答by asifsid88
If you want the function to be called on click then use
如果您希望在单击时调用该函数,请使用
$("bereken").on('click', btw_bijtellen);
Update (As per query from WAO)
更新(根据 WAO 的查询)
If you need to pass the argument, then you need to specify as the second argument. the $.on()
gets the data in the event
handler
如果需要传递参数,则需要指定为第二个参数。将$.on()
得到的数据event
处理程序
$("bereken").on('click', {key1: value1, key2: value2, keyn: valuen}, btw_bijtellen);
where, you can get your parameters from event.data
你可以从哪里得到你的参数 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
}
Have a read on this link jQuery $.on() api
阅读此链接jQuery $.on() api
回答by Quentin
Putting ()
after a function name is how you call it.
放在()
函数名之后就是你调用它的方式。
If you want to assign the btw_bijtellen
to onclick
then remove the ()
from the last line of the code in the question.
如果您想分配btw_bijtellen
toonclick
然后()
从问题代码的最后一行中删除。
With the ()
there, you are calling the function and assigning its return valueto onclick
. Since that function has no return
statement, that value will be undefined
which is not what you want.
在()
那里,您正在调用该函数并将其返回值分配给onclick
. 由于该函数没有return
声明,因此该值将undefined
不是您想要的。