简体   繁体   English

使用jQuery移除父元素

[英]Removing Parent Elements with jQuery

So I'm working on a small web app where the user creates a list and it is formatted and emailed back to them. 因此,我正在开发一个小型Web应用程序,在该应用程序中,用户创建了一个列表,并将其格式化并通过电子邮件发送给他们。 Anyway, I am having trouble creating a functioning way to delete list items without clearing everything. 无论如何,我在创建删除列表项而不清除所有内容的有效方式时遇到了麻烦。

Here is a Fiddle http://jsfiddle.net/mRWt6/ 这是小提琴http://jsfiddle.net/mRWt6/

The jquery Code to add/delete items jQuery代码添加/删除项目

function deleteItem(){
    $(this).closest('div').remove();
}
function addItem(){
    var item = $('#newItem').val();
    $('#list').append('<div><span>'+item+'</span><button class="delete">X</button></div>');
    $('#newItem').val('');
}

$(function() {
    $('.delete').on('click', deleteItem);
    $('#add').on('click', addItem);
});

The first example that I created manually works as intended, but the new items that are added don't work at all. 我手动创建的第一个示例可以按预期工作,但是添加的新项目根本无法工作。 What's going on here? 这里发生了什么? I'm pretty new to Javascript and jQuery so detailed explanations are appreciated! 我对Javascript和jQuery还是很陌生,所以详细的解释值得赞赏!

delegate event to closest static container: 将事件委托给最接近的静态容器:

$('#list').on('click', '.delete', deleteItem);

More info here: http://learn.jquery.com/events/event-delegation/ 此处提供更多信息: http : //learn.jquery.com/events/event-delegation/

Use .on() 使用.on()

Use Event Delegation . 使用事件委托

$('#list').on('click', '.delete', deleteItem);

Syntax 句法

$( elements ).on( events, selector, data, handler );

fiddle Demo 小提琴演示

You need to use event delegation 您需要使用事件委托

Use 采用

$('#list').on('click','.delete', deleteItem);

DEMO DEMO

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM