Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery: Why would selector fail?

<html>
 <head>
  <script src="../jquery.js" type="text/javascript"> </script>
  <script type="text/javascript">
   $(".demo").click(function() {
     alert("JavaScript Demo");
    });
  </script>
 </head>
 <body>
  <p class="demo">a paragraph</p>
 </body>
</html>

Why did not the click function response?

Thanks.

like image 346
Jichao Avatar asked Aug 01 '26 20:08

Jichao


2 Answers

You are running the code too early. You should wrap it in a document-ready handler, which jQuery supports thus:

$(function() {
  $(".demo").click(function() {
    alert("JavaScript Demo");
  });

  // Put other initialisation code here...
});

This will ensure that your code runs after the document is loaded.

like image 89
Marcelo Cantos Avatar answered Aug 04 '26 11:08

Marcelo Cantos


You are running the code when the DOM isn't ready yet.

There are 2 solutions:


Solution One:

Add the Javascript after the elements it affects. Preferably as far down the page as possible.

Doing this is not always possible, but it is suggested by YUI for speeding up your website.

<html>
 <head>
  <script src="../jquery.js" type="text/javascript"> </script>
 </head>
 <body>
  <p class="demo">a paragraph</p>
  <script type="text/javascript">
     // This is after .demo
   $(".demo").click(function() {
     alert("JavaScript Demo");
    });
  </script>
 </body>
</html>


Solution Two:

Wrap your script in a doc ready. In jQuery there are several forms. The quickest to type is $(function() { ... });:

<html>
 <head>
  <script src="../jquery.js" type="text/javascript"> </script>
  <script type="text/javascript">
     // doc ready
   $(function() {            
     $(".demo").click(function() {
       alert("JavaScript Demo");
      });
   });
  </script>
 </head>
 <body>
  <p class="demo">a paragraph</p>
 </body>
</html>
like image 20
Peter Ajtai Avatar answered Aug 04 '26 10:08

Peter Ajtai



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!