jQuery中动态添加的元素的事件委托问题 [英] Event delegate issue for dynamically added element in jquery

查看:316
本文介绍了jQuery中动态添加的元素的事件委托问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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/

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

I can't bind event to element that created dynamically. How can I do it?

推荐答案

您误解了事件委托.事件委托是通过最接近的div完成的.在这里,我使用了document,但是您可以使用最接近的div来将其用作事件委托.

You are misunderstanding event delegation. Event delegation is done with the closest div. Here I have used document but you can use the closest div to use it as event delegation.

使用此:

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

演示

这是了解事件委托

示例:

// 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() );
});

这篇关于jQuery中动态添加的元素的事件委托问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆