【问题标题】:How to Detect Changes on New Radio Buttons?如何检测新单选按钮的变化?
【发布时间】:2014-02-05 15:52:27
【问题描述】:

我有检测单选按钮更改然后调用按钮上的方法的代码。它适用于现有按钮,但是当我向页面添加新的单选按钮时(通过 ajax),它不适用于它们。如何让它检测新单选按钮上的更改?

这是我的咖啡脚本代码:

jQuery ->
    $(".radio-button:radio").change ->
        doSomething(this)

在 JS 中是这样的:

jQuery(function() {
  return $(".radio-button:radio").change(function() {
    return doSomething(this);
  });
});

【问题讨论】:

    标签: jquery ruby-on-rails coffeescript radio-button jquery-events


    【解决方案1】:

    对于动态创建的元素,您需要使用.on() 进行事件委托

    $(document).on('change','.radio-button:radio', function() {
        //Your code here
    });
    

    而不是(用于静态元素)

    $(".radio-button:radio").change(function() {
        //Your code
    });
    

    注意:您需要将 $(document) 替换为 DOM 中存在的静态父选择器 $(parent) 并使用它以获得更好的性能。

    【讨论】:

    • 谢谢。页面加载时不存在下级父级,所以我想我会坚持使用文档。
    猜你喜欢
    • 2011-08-02
    • 2019-01-11
    • 2018-01-22
    • 1970-01-01
    • 2018-09-04
    • 2014-10-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多