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=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/
Doing:
…is the same as
…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
clickhandler to#but2was running before#but2had loaded onto the page.