添加事件处理程序,以新创建的元素
问题描述:
我尝试新的元素添加到有序列表与链接,它的去除:添加事件处理程序,以新创建的元素
$('#list ol').append('<li>' + label + ' <a href="#remove_'+id+'">[remove]</a></li>');
,但是这是行不通的:
$('a[href^="#remove"]').on('click', function(event){
alert('Removing: '+$(this).attr('href').substr(8));
event.preventDefault();
});
知道为什么?
答
将jQuery标签中的新元素换行并在当时应用事件处理程序。这比使用比较复杂的jQuery选择的元素已经被插入到DOM后,事件处理函数分配一个更清洁,更有效的方法:
//this line will create your element in memory, but not insert it to the DOM
var newElmt = $('<li>' + label + ' <a href="#remove_'+id+'">[remove]</a></li>');
//you can apply jQuery style event handlers at this point
newElmt.on('click',function(e) {
alert('Removing: '+$(this).attr('href').substr(8));
event.preventDefault();
});
//insert the element as you were before
$('#list ol').append(newElmt);
答
$('#list').on('click', 'a[href^="#remove"]', function(event){
alert('Removing: '+$(this).attr('href').substr(8));
event.preventDefault();
});
当你追加li
动态,所以您需要使用.on()
作为委托处理程序来委托事件处理。