开发者

Why isn't jQuery binding with click?

Why isn't jQuery binding to the click event? When I click the selects, they don't ale开发者_如何学Pythonrt, except for the one that I put onClick on.

<html>
<head>
<title>Robo</title>

<script type="text/javascript" src="jquery-1.4.2.min.js"></script><script type="text/javascript">

$('.changer').click(function(){alert('test');});


</script>
</head>
<body>

<select class="changer" name="dept" id="dept_select">
    <option value="">Select a Department</option>
</select>

<select onclick="alert('ya');" class="changer" name="course" id="course_select">
    <option value="">Select a Course</option>
</select>
<select class="changer" name="section" id="section_select">
    <option value="">Select a Section</option>
</select>

</body>
</html>


Because the .changer elements are not available in the dom when you are binding the click handlers. You can do two things:

Use jQuery ready event handler

 $.ready(function(){
      $('.changer').click(function(){
        alert('test');
      });
    });

or Use live function.

$('.changer').live("click", (function(){
   alert('test');
 });


You need to wrap your code in ready handler:

$(function(){
  $('.changer').click(function(){alert('test');});
});


Wrap your jQuery in a ready event:

$(function() {
    $('.changer').click(function(){alert('test');});
});


you can also use delegate function...

$('.changer').delegate('click',function(){
   alert('test'); 
 });


You have to wrap syntax dg .ready handler.

<script type="text/javascript">
$(document).ready( function(){
   $('.changer').click(function(){alert('test');});
});
</script>

It's method used to specify a function to execute when the DOM is fully loaded.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜