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

有帮助吗?

解决方案

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')); 
});
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top