Jquery not applying on dynamic elements created in context menu

帅比萌擦擦* 提交于 2019-12-11 12:19:34

问题


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')); 
});


来源:https://stackoverflow.com/questions/19457672/jquery-not-applying-on-dynamic-elements-created-in-context-menu

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!