2

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.

1
  • It is because at the moment the event handler should be attached, jQuery cannot find the element with ID but2 as the DOM is not loaded yet. Either move the script to the button of the page or, and this is the preferred solution, do as Patrick suggests. Commented Jul 31, 2010 at 16:59

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

2 Comments

"patrick dw"'s method works!! Thank you so much!! By the way, there is a small problem with the code from jsfiddle.net/ApDKU. If some one copy the js code directly from 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 - 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)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.