Jquery not applying on dynamic elements created in

2019-07-27 17:51发布

问题:

I have a script containing $('a').on('click', function () {alert($(this).attr('class')); }); In my contextmenu function, I create a list with links

$(function () {
$('a').on('contextmenu', function (event) {
        $("<ul id='menu'></ul>")
        .append('<li><a href="#" class="test">Test 1</a></li>')
        .append('<li><a href="">Test 2</a></li>')
        .appendTo("body")
        .css({ top: event.pageY + "px", left: event.pageX + "px" });
        return false;
    });

});

However, the first piece of code (the on click event) does not fire when the link in the list is clicked. However, it fires for every other link on the page. How can I fix this so that my script works on dynamic elements

回答1:

Just a rehash of another SO question.

Calling the jQuery on method on $(document) and providing the 'selector' option will bind the callback to dynamically added elements matching the selector parameter.

That is, this:

$(document).on('click', 'a', function () {
  alert( $(this).attr('class') ); 
});

instead of this:

$('a').on('click', function () {
  alert($(this).attr('class')); 
});