【问题标题】:jquery dynamically added checkbox not working with change() functionjquery 动态添加的复选框不适用于 change() 函数
【发布时间】:2011-06-09 04:50:41
【问题描述】:

我动态加载了几个 li,其中有一个标签和一个复选框到另一个可见的 ul。我将复选框设置为checked="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>

知道为什么当复选框更改其选中状态时我无法发出警报吗?

【问题讨论】:

    标签: jquery dynamic checkbox onchange


    【解决方案1】:

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

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

    编辑 要在 IE 中工作,您必须使用 click not change

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

    【讨论】:

    • @Teja Kantamneni:完美。感谢您的指导。还在学习 jquery 的来龙去脉。
    • 只有在设置了事件处理程序之后添加元素时,您才需要这样做。
    • @Gareth:嗯,现在说得通了。
    • 这就是IE的问题,IE只有在元素失去焦点后才会触发change事件。 webbugtrack.blogspot.com/2007/11/…
    • 要修复,请使用click 而不是change
    【解决方案2】:

    从 jQuery 1.7 开始的 live() is now deprecated 开始,我想我会发布对同一问题有用的解决方案(更改动态添加的复选框时的触发事件)。

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

    【讨论】:

    • document.getElementById('id').live('click',function() { alert('test'); });它对我不起作用..“otherProductCheckbox”在这里是什么意思?
    【解决方案3】:

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

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-01-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多