向新创建的元素添加事件处理程序 [英] Adding event handler to newly created element

查看:148
本文介绍了向新创建的元素添加事件处理程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试添加新的元素到订单列表中,链接被删除:

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

但这不工作:



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

任何想法为什么?

解决方案

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

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

这篇关于向新创建的元素添加事件处理程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆