为什么单击事件处理程序会在页面加载后立即触发? [英] Why does click event handler fire immediately upon page load?
问题描述
我在玩一个我想绑定到所有链接的函数.目前,该功能在页面加载时触发,而不是在我单击链接时触发.
I playing around with a function that I want to bind to all the links. At the present the function fires when the page loads, instead of when I click on the link.
这是我的代码. (如果需要查看,我可以发布功能showDiv()
.)您能告诉我在这里做错了还是愚蠢的事情?
Here's my code. (I can post the function showDiv()
, if you need to see it.) Can you tell if I'm doing something wrong or stupid here?
$(document).ready(function(){
$('a.test').bind("click", showDiv());
});
谢谢!
推荐答案
您想将引用作为回调传递给函数,而不是函数执行的结果:
You want to pass a reference to a function as a callback, and not the result of function execution:
showDiv()
返回一些值;如果未使用return
语句,则返回undefined
.
showDiv()
returns some value; if no return
statement was used, undefined
is returned.
showDiv
是对应执行功能的引用.
showDiv
is a reference to the function that should be executed.
这应该有效:
$(document).ready(function(){
$('a.test').bind("click", showDiv);
});
或者,您可以使用匿名函数来执行更高级的功能:
Alternatively, you could use an anonymous function to perform a more advanced function:
...bind('click', function(){
foo.showDiv(a,b,c);
...more code...
});
在某些情况下,您可能想要使用函数返回的值作为回调:
In some circumstances you may want to use the value returned by a function as a callback:
function function foo(which)
{
function bar()
{
console.log('so very true');
}
function baz()
{
console.log('no way!');
}
return which ? bar : baz;
}
...click( foo( fizz ) );
在此示例中,使用fizz
评估foo
并返回一个函数,该函数将被分配为click事件的回调.
In this example, foo
is evaluated using fizz
and returns a function that will be assigned as the callback for the click event.
这篇关于为什么单击事件处理程序会在页面加载后立即触发?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!