admin管理员组

文章数量:1323714

I have the following code.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" ".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>

When I run this code then alert(5) is ing 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?

I have the following code.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3/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>

When I run this code then alert(5) is ing 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?

Share Improve this question edited Jun 8, 2012 at 12:16 Felix Kling 817k181 gold badges1.1k silver badges1.2k bronze badges asked Jun 8, 2012 at 11:15 SearcherSearcher 1,8559 gold badges32 silver badges45 bronze badges 1
  • developer.mozilla/en/JavaScript/Guide/Functions might be helpful to understand functions better. – Felix Kling Commented Jun 8, 2012 at 12:13
Add a ment  | 

4 Answers 4

Reset to default 10
$("#myID").click(myFun());

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.

Read this .click() - Bind an event handler to the click JavaScript event, or trigger that event on an element using JavaScript.

You just need to write $("#myID").click(myFun); instead of $("#myID").click(myFun()); because when you write myFun() in your code the function is invoked immediately (rather than when a click event fires on #myID).

Working Demo

Try this for running the function on the click event:

function myFun(){
    alert(5);
}

$(document).ready(function(){
    $("#myID").click(function(){
        myFun();
    });
})

Try this:

This will work

$(document).ready(function() {
    function myFun() {
        alert(5)
    }
            $("#myID").click(function(){
            myFun();
            });
});​

本文标签: javascriptDifference between click(handler()) and click(handler)Stack Overflow