Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery selector doesn't work

The code

<script type="text/javascript" src="jquery/jquery-1.8.0.js"></script>  
<script type="text/javascript">  
$(document).ready(function() {  
    alert("Hello!");  
});  
$(".demo").click(function() {  
    alert("I am demo");  
});  
</script>  
<body>  
    <button class="demo">click me</button>  
</body>  

The first Hello! is OK, but I am demo can't?What's the matter?

the similar question jquery each selector doesnt work

like image 369
suannai Avatar asked Sep 26 '26 21:09

suannai


1 Answers

Your click event handler is trying to bind to the demo button before the HTML body has rendered. You need to assign the event handler inside your $(document).ready function:

Change this:

$(document).ready(function() {  
    alert("Hello!");  
});  
$(".demo").click(function() {  
    alert("I am demo");  
});

To this:

$(document).ready(function() {  
    alert("Hello!");  
    $(".demo").click(function() {  
        alert("I am demo");  
    });
});  
like image 131
Elliot B. Avatar answered Sep 29 '26 11:09

Elliot B.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!