jQuery.on()未触发

jQuery.on()未触发,jquery,Jquery,我正在使用引导下拉列表,向其中动态添加新项。但是,没有为动态添加的项目触发on()事件。为什么? $('div.my-modal .some-class label.link').off(); $('div.my-modal .some-class label.link').on('click',function () { console.log('a'); }); ... $('div.my-modal .some-class').append("<li><lab

我正在使用引导下拉列表,向其中动态添加新项。但是,没有为动态添加的项目触发
on()
事件。为什么?

$('div.my-modal .some-class label.link').off();
$('div.my-modal .some-class label.link').on('click',function () {
     console.log('a');
});

...
$('div.my-modal .some-class').append("<li><label class='link'>test</label></li>");
$('div.my-modal.some class label.link').off();
$('div.my-modal.some class label.link')。在('click',函数(){
console.log('a');
});
...
$('div.my-modal.some class')。追加(“
  • 测试”
  • ”;
    您可以使用带有文档的方法
    .on()
    将事件直接绑定到类,因为实例不存在
    试试这个:

    $(document).on('click','div.my-modal .some-class label.link', function () {
         console.log('a');
    });
    

    只要
    .on()
    知道所有元素都已创建
    .on()
    在需要启动事件处理程序或重新加载页面之前不会被激发-除非您将其绑定到文档之类的更改(正如alessandro minoccheri所说)是的,它可以工作。告诉我,在这种情况下,我必须在.on()方法之前使用.off()吗?包含该代码的页面可以多次加载,我想防止事件冒泡。如果需要,需要使用off()。on()不触发,例如禁用按钮事件。在这种情况下,我认为这是没有必要的,就像旧的unbind()事件@Tony一样