开发者

JQuery button is not displaying an alert

I am learning jquery and I am having difficulty running the following extremely simple code.

My HTML looks like:

<html>
<head>
    <title>JQUERY</title>
    <script type="text/javascript" src="http://ajax.googleapis.com开发者_开发技巧/ajax/libs/jquery/1.4.0/jquery.min.js"></script>
    <script type="text/javascript" src="script.js"></script>
</head>
<body>

<input type="button" id="testbutton" value="test" />

</body>

My script.js looks like this:

$(document).ready(function(){
  alert('document is ready');
});
$('#testbutton').click(function(){
  alert('button clicked');
});

When I load the page in browser ... I get the first alert when the document is loaded (so I am sure that I am at least using the correct library and it is getting downloaded etc).

However, when I click my button I do not see the second alert that says "button has been clicked"

What am I missing?


The click handler needs to go inside your $(document).ready, to ensure that it is bound when the DOM is ready, and the element is guaranteed to be available for Javascript processing:

$(document).ready(function(){
    alert('document is ready');

    // bind a click handler to #testbutton when the DOM has loaded
    $('#testbutton').click(function(){
      alert('button clicked');
    });
});

From the documentation:

This is the first thing to learn about jQuery: If you want an event to work on your page, you should call it inside the $(document).ready() function. Everything inside it will load as soon as the DOM is loaded and before the page contents are loaded.


You probably want to bind your event handler inside the $(document).ready() event:

$(document).ready(function(){
  alert('document is ready');

  $('#testbutton').click(function(){
   alert('button clicked');
  });
});

This makes sure the DOM is loaded before your other script gets executed. See if this solves your problem.


You also need that click binding inside a document.ready, like this:

$(function(){      //short for $(document).ready(function(){
  alert('document is ready');
  $('#testbutton').click(function(){
    alert('button clicked');
  });
});

The why? is that the selector $('#testbutton') won't find the element id="testbutton" if it's not ready when the selector runs, so it needs to be run after the element in the page, or in a document.ready handler like above.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜