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
4 Answers
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
版权声明:本文标题:javascript - Difference between `.click(handler())` and `.click(handler)` - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742127979a2422029.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论