views:

28

answers:

1

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.

+2  A: 

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.

patrick dw
"patrick dw"'s method works!! Thank you so much!!By the way, there is a small problem with the code from http://jsfiddle.net/ApDKU/. If some one copy the js code directly from http://jsfiddle.net/ApDKU/, there are some invisible characters included and the code doesn't run. I noticed it in firebug. I deleted the invisible characters and the code run like a charm.
peter
@peter - Yeah, I don't know what those characters are. They're always there, and they really mess me up sometimes. Glad you got it working. :o)
patrick dw