简体   繁体   中英

Why is my event handler bound with jQuery not firing?

Any ideas why this doesnt work in my php document? When i tested this on jsfiddle, everything worked fine.

<head>
    <script type="text/javascript" src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
    <script type="text/javascript">
        $("a").click(function() {
            $("div.info").hide();
            $("div." + this.className).show();
        });
    </script>
</head>

<body>
    <div class="shipping-container">
        <a href="#" class="ups">Show UPS info</a>
        <a href="#" class="fedex">Show Fedex info</a>
        <div class="ups info" style="display:none">the info for ups</div>
        <div class="fedex info" style="display:none">Who let the dogs out</div>
    </div>
</body>

You missed the document ready handler, try this:

<script type="text/javascript">
    $(function() {
        $("a").click(function() {
            $("div.info").hide();
            $("div." + this.className).show();
        });
    });
</script>

Alternatively, leave your script tag as it is, but put it at the end of the document, before the </body> tag.

You should make sure that your JQuery code is only loaded AFTER your DOM has fully loaded by doing:

$(document).ready(function() {

   $("a").click(function() {
       $("div.info").hide();
       $("div." + this.className).show();
   });

});

You are running the script before the link element exists.

In jsfiddle the code is by default placed in an event that runs after the document is loaded. Use the ready event to do this in your code:

<script type="text/javascript">
$(document).ready(function(){
  $("a").click(function() {
    $("div.info").hide();
    $("div." + this.className).show();
  });
});
</script>

I think you should do this in your header:

<script type="text/javascript">
$(document).ready(function() {
  $("a").click(function() {
      $("div.info").hide();
      $("div." + this.className).show();

});
</script>

This will ensure that all of the DOM objects (especially the a elements) are loaded before you try to attach any event handler.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM