将事件处理程序添加到新创建的元素

use*_*241 5 jquery dom

我正在尝试将新元素添加到有序列表中,并为其删除链接:

$('#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)

知道为什么吗?

Ell*_* B. 8

在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)