为什么点击事件处理程序在页面加载时立即触发? [英] Why does click event handler fire immediately upon page load?

查看:43
本文介绍了为什么点击事件处理程序在页面加载时立即触发?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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').on("click", showDiv); // jQuery 1.7 and higher
  $('a.test').bind("click", showDiv); // jQuery 1.6 and lower
});

或者,您可以使用匿名函数来执行更高级的功能:

Alternatively, you could use an anonymous function to perform a more advanced function:

// jQuery 1.7 and higher
el.on('click', function() {
  foo.showDiv(a, b, c);
  // more code...
});

// jQuery 1.6 and lower
el.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;
}

el.click(foo(fizz));

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

In this example, foo is evaluated using fizz and returns a function that will be assigned as the callback for the click event.

这篇关于为什么点击事件处理程序在页面加载时立即触发?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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