简体   繁体   中英

jQuery click event not firing on hyperlink

I am using jquery 2.1.4

I dynamically create a list with hyperlinks to trigger a function.

$.getJSON('json_data.php', { method: 'getCertifications', userId: userId }, function(data) {
          $.each(data, function(key, value) {
             i++;
             $("#certificationCount").text("Total - " + i);
             $("#userCertifications").append('<div class="usercert"><li>' + value.certName + '</li><a href="#" data-id="' + value.certName + '">X</a></div>');
          });
      });

Then I want to call a function when a user clicks on the "X" hyperlink. However, the function is not being called.

$(document).ready(function() {
       $(".usercert a").on('click', 'a', function(e) {
          console.log("It works!");
          alert("It works!");
       });
    });

Why is the function inside the document ready not firing?

This boils down to what looks like a bit of a misunderstanding of delegated event handlers in jQuery.

You have:

$(".usercert a").on('click', 'a', function(e) {
   console.log("It works!");
   alert("It works!");
});

But you probably want:

$("#userCertifications").on('click', '.usercert a', function(e) {
   console.log("It works!");
   alert("It works!");
});

First you bind to an element that exists at the time of binding, in this case that would be the #userCertifications element (I make this assumption based on the fact that you are appending elements to this element in your AJAX callback). That way you've actually selected something, so the .on() method call is actually doing something.

Second you'd tell .on() what selector you'd like to match for your delegated event handler. In this case we'd use .usercert a because each of the elements we want to run the event handler for will match this selector: #userCertifications .usercert a .

Documentation for jQuery's .on() : http://api.jquery.com/on/#on-events-selector-data

$(document).ready is firing before you make your asynchronous call, so those hrefs haven't yet been populated. Rebind the clicks after you fetch your data.

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