`.click(handler())`和`.click(handler)`之间的区别 [英] Difference between `.click(handler())` and `.click(handler)`

查看:345
本文介绍了`.click(handler())`和`.click(handler)`之间的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码。

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
 <head>
    <script type="text/javascript" src="jquery-1.4.2.min.js" ></script>
    <script type="text/javascript">
    function myFun()
    {
        alert(5)
    }
        $(document).ready(function(){
            $("#myID").click(myFun());
        })
    </script>
 </head>

 <body>
  <input type="button" value="Click it" id="myID" />
 </body>
</html>

当我运行此代码时, alert(5)即将到来。如果我写

When I run this code then alert(5) is coming when the page loads. If I write

$("#myID").click(myFun)

然后只有当我们点击按钮时才会出现警报。为什么它会这样?

then the alert only appears when we click on the button. Why does it behave like this?

推荐答案

$("#myID").click(myFun());

这会调用 myFun()并尝试安装它返回的任何事件处理程序。由于它没有返回任何内容,实际上触发点击 #myID

This calls myFun() and tries to install whatever it returns as an event handler. Since it is not returning anything, you are actually triggering the click on #myID.

这篇关于`.click(handler())`和`.click(handler)`之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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