jquery动态添加复选框不能与change()函数一起使用

时间:2011-01-14 14:49:38

标签: jquery dynamic checkbox onchange

我动态加载了一些带有标签和复选框的li到另一个可见的ul。我将复选框设置为check =“checked”,我试图触发一个事件,当我更改这些动态插入的复选框但没有发生时。

这是jquery:

$(".otherProductCheckbox:checkbox").change( function(){
    alert('test');
});

以下是动态添加的li的html:

<li class="otherProduct"><input type="checkbox" class="otherProductCheckbox radioCheck" checked="checked"/><label>Product Name</label></li>

我知道为什么当复选框更改其选中状态时,我无法获得警报?

3 个答案:

答案 0 :(得分:19)

您必须使用liveQuerylive将事件绑定到动态添加的元素。

$(".otherProductCheckbox:checkbox").live('change', function(){
    alert('test');
});

修改 要在IE中工作,您必须使用click not change

$(".otherProductCheckbox:checkbox").live('click', function(){
        alert('test');
 });

答案 1 :(得分:17)

自jQuery 1.7起live() is now deprecated以来,我认为我会发布针对同一问题的解决方案(动态添加复选框时更改触发事件)。

$(document).on('click', '.otherProductCheckbox', function() {
    alert('test');
});

答案 2 :(得分:0)

以上两种方法都不适合我,但是当为列表视图中的项目列表动态添加复选框时,这个方法起作用。

$('.favourite_itemList').on('click','.checkBox', function () {
   alert('test')
)};

尽管在 optIn 或 optOut 时特定复选框元素中没有显示可见的功能/属性更改,但上述代码对我来说效果很好。