jQuery不适用于上下文菜单中创建的动态元素 [英] Jquery not applying on dynamic elements created in context menu

查看:103
本文介绍了jQuery不适用于上下文菜单中创建的动态元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含$('a').on('click', function () {alert($(this).attr('class')); });的脚本 在我的contextmenu函数中,我创建了一个带有链接的列表

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

});

但是,当单击列表中的链接时,第一段代码(on click事件)不会触发.但是,它会为页面上的所有其他链接触发.如何解决此问题,以便我的脚本可以处理动态元素

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

推荐答案

只是重新讨论了另一个 SO问题.

Just a rehash of another SO question.

在$ {document)上调用jQuery on方法并提供选择器"选项会将回调绑定到与选择器参数匹配的动态添加的元素.

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

也就是说,这个:

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

代替此:

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

这篇关于jQuery不适用于上下文菜单中创建的动态元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆