我正在尝试将新元素添加到有序列表中,并为其删除链接:
$('#list ol').append('<li>' + label + ' <a href="#remove_'+id+'">[remove]</a></li>');
Run Code Online (Sandbox Code Playgroud)
但这不起作用:
$('a[href^="#remove"]').on('click', function(event){
alert('Removing: '+$(this).attr('href').substr(8));
event.preventDefault();
});
Run Code Online (Sandbox Code Playgroud)
知道为什么吗?
在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);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2427 次 |
| 最近记录: |