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/
我无法将事件绑定到动态创建的元素.我该怎么做?
解决方法
你是对事件授权的误解.事件委派是使用最近的div完成的.这里我使用了文档,但您可以使用最近的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() );
});