【问题标题】:Event delegate issue for dynamically added element in jqueryjquery中动态添加元素的事件委托问题
【发布时间】:2014-01-09 11:59:11
【问题描述】:

HTML

<table>
<tr>
    <td>Col</td>
    <td>:</td>
    <td>
        <input type="text" name="" class="check-input" />
        <span class="error-input"></span>
    </td>
    <td><button class="add-input">Click</button></td>
</tr>
</table>

JQUERY

$('.add-input').on('click',function(){
    $(this).closest('tr').after('<tr><td>Col</td><td>:</td><td><input type="text" name="" class="check-input" /><span class="error-input"></span></td><td></td></tr>');
});

$('.check-input').on('change',function(){
    $(this).next().text('Error');
});

http://jsfiddle.net/ch2FM/3/

我无法将事件绑定到动态创建的元素。我该怎么做?

【问题讨论】:

    标签: jquery


    【解决方案1】:

    您误解了事件委托。事件委托使用最近的 div 完成。这里我使用了document,但是你可以使用最近的div来作为事件委托。

    使用这个:

    $(document).on('change','.check-input',function(){
        $(this).next().text('Error');
     });
    

    demo


    这里是了解event delegation的链接

    例子:

    // attach a directly bound event
    $( "#list a" ).on( "click", function( event ) {
    event.preventDefault();
    console.log( $( this ).text() );
    });
    
    // attach a delegated event
    $( "#list" ).on( "click", "a", function( event ) {
    event.preventDefault();
    console.log( $( this ).text() );
    });
    

    【讨论】:

    • “事件委托是用最近的 div 完成的” - 更像是“最近的静态父元素”... :)
    【解决方案2】:

    试试这个

    $(document).on('change','.check-input',function(){
        $(this).next().text('Error');
     });
    

    DEMO

    【讨论】:

      【解决方案3】:

      您需要将on 处理程序分配给祖先元素,例如document 元素。然后,您可以指定要侦听的元素的确切选择器作为第二个参数:

      $(document).on('change', '.check-input', function () {
          $(this).next().text('Error');
      });
      

      这基本上意味着:侦听作为document 元素后代的所有.check-input 元素的change 事件。

      Here is a working example

      【讨论】:

        猜你喜欢
        • 2021-11-02
        • 1970-01-01
        • 1970-01-01
        • 2012-08-14
        • 1970-01-01
        • 2011-06-04
        • 1970-01-01
        • 2012-12-18
        • 2013-10-23
        相关资源
        最近更新 更多