在jquery中动态添加元素的事件委托问题
HTML
Col :
JQUERY
$('.add-input').on('click',function(){ $(this).closest('tr').after('Col : '); }); $('.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'); });
演示
这是了解事件委托的链接
例:
// 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() ); });
试试这个
$(document).on('change','.check-input',function(){ $(this).next().text('Error'); });
DEMO
您需要为祖先元素分配on
处理程序,例如document
元素。 然后,您可以指定要侦听的元素的确切选择器作为第二个参数:
$(document).on('change', '.check-input', function () { $(this).next().text('Error'); });
这基本上意味着:监听作为document
元素后代的所有.check-input
元素的change
事件。
这是一个有效的例子