且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2023-10-10 09:35:40

在jQuery标签中包装新的元素,并应用当时的事件处理程序。这是比使用某些复杂的jQuery选择器在元素已被插入到DOM中之后分配事件处理程序的一种更清洁和更有效的方法:

  //这行将在内存中创建您的元素,但不会将其插入DOM 
var newElmt = $('< li>'+ label +'< a href =#remove_' + ID + '&GT; [删除]&LT; / A&GT;&LT; /立GT;');

//此时您可以应用jQuery风格的事件处理程序
newElmt.on('click',function(e){

alert(' '+ $(this).attr('href')。substr(8));
event.preventDefault();
});

//在
$('#list ol')之前插入元素。append(newElmt);


I'm trying to add new element to ordered list with link for it's removal:

$('#list ol').append('<li>' + label + ' <a href="#remove_'+id+'">[remove]</a></li>');

but this is not working:

$('a[href^="#remove"]').on('click', function(event){
    alert('Removing: '+$(this).attr('href').substr(8));
    event.preventDefault();
});

Any idea why?

Wrap up the new element in jQuery tags and apply the event handler at that time. This is a cleaner and more efficient approach than using somewhat complicated jQuery selectors to assign the event handler after the element has already been inserted into the 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);