jQuery 为什么点击事件处理程序在页面加载时立即触发?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7102413/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 23:24:05  来源:igfitidea点击:

Why does click event handler fire immediately upon page load?

jquerybind

提问by Jeff

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.

我玩弄一个我想绑定到所有链接的函数。目前,该功能在页面加载时触发,而不是在我单击链接时触发。

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?

这是我的代码。(showDiv()如果您需要查看它,我可以发布该功能。)您能告诉我我在这里做错了还是做错了?

$(document).ready(function(){

    $('a.test').bind("click", showDiv());

});

Thanks!

谢谢!

回答by zzzzBov

You want to pass a referenceto a function as a callback, and not the result of function execution:

您希望将函数引用作为回调传递,而不是函数执行的结果:

showDiv()returns some value; if no returnstatement was used, undefinedis returned.

showDiv()返回一些值;如果没有使用return语句,undefined则返回。

showDivis a reference to the function that should be executed.

showDiv是对应该执行的函数的引用。

This should work:

这应该有效:

$(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 wantto 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 ) );

In this example, foois evaluated using fizzand returns a function that will be assigned as the callback for the click event.

在此示例中,foo使用fizz并返回一个函数进行评估,该函数将被分配为单击事件的回调。

回答by tjarratt

Looks like you're calling the function showDiv directly there (and binding the return result of showDiv() to the click handler instead of binding it directly.

看起来你是直接在那里调用函数 showDiv (并将 showDiv() 的返回结果绑定到点击处理程序而不是直接绑定它。

You want something like

你想要类似的东西

$(document).ready(function() { $('a.test').bind("click", showDiv); });

回答by ShankarSangoli

Use the below line. showDiv()will call the function rigth away when that line is executed.

使用下面的行。 showDiv()将在执行该行时立即调用该函数。

$('a.test').bind("click", showDiv);

回答by Mrchief

Change it to: $('a.test').bind("click", showDiv);(do not put parens around showDivsince you want to pass the function reference).

将其更改为:($('a.test').bind("click", showDiv);不要放置括号,showDiv因为您要传递函数引用)。