jquery bind button click event fails
test.html:
<html>
<head>
<script type="text/javascript" src="jquery-1.4.2.js"></script>
<script type="text/javascript" src="test.js"></script>
</head>
<body>
<input id="but2" type="button" value="2"/>
</body>
</html>
jquery-1.4.2.js is downloaded from http://jquery.com/
test.js:
var fn=开发者_JS百科function(){
alert('success!');
};
$('#but2').click(fn);
When clicked the button, nothing happened. I debugged for very long time but didn't find the root cause. Please help.
Wrap it such that the code doesn't run until the document has loaded.
Try it out: http://jsfiddle.net/ApDKU/
$(function() {
var fn=function(){
alert('success!');
};
$('#but2').click(fn);
});
Doing:
$(function() {...});
...is the same as
$(document).ready(function() {...});
...which cause the code inside to run only after the <body>
tag has finished loading.
The way you had it, the code that attached the click
handler to #but2
was running before #but2
had loaded onto the page.
精彩评论