我正在尝试将新元素添加到有序列表中,并带有删除链接:
$('#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 标记中,然后应用事件处理程序。与在元素插入 DOM 后使用稍微复杂的 jQuery 选择器分配事件处理程序相比,这是一种更干净、更有效的方法:
//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);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)