简体   繁体   English

删除动态生成的元素

[英]Removing a dynamically generated element

I have implemented a user-generated keyword list for a project I'm working on, using jQueryUI autocomplete to suggest existing keywords. 我已经为我正在使用的项目实现了一个用户生成的关键字列表,使用jQueryUI自动完成来建议现有的关键字。

On selecting the autocomplete suggestion, the returned string is added to the html of a div , as a child div. 在选择自动完成建议时,返回的字符串将添加到div的html中,作为子div。

I would like to add a removal function whereby the user can remove the child div if erroneously entered. 我想添加一个删除功能,用户可以在错误输入时删除子div。

I've tried multiple suggested answers from Stackoverflow and elsewhere, but can't seem to get it working. 我已尝试过Stackoverflow和其他地方的多个建议答案,但似乎无法使其正常工作。

I've created a fiddle containing the pertinent elements. 我创造了一个包含相关元素的小提琴

The most logical solution to me was: 对我来说最合乎逻辑的解决方案是:

$('.keyword-entry').click(function(e){
    var id = $(this).closest('div').prop('id');
    $('#'+id).remove();
}

Though it would appear this doesn't work. 虽然看起来这不起作用。

Whilst a solution to the problem would be very much appreciated to save my dwindling supply of coffee from running out this evening, I would also appreciate a rundown as to why I'm going wrong. 虽然能够解决这个问题,但是为了节省我今天晚上用完的咖啡供应减少,我还要感谢我为什么会出错。

Thanks in advance. 提前致谢。

Event delegation. 活动代表团。

It's basically that you're attempting to attach an event to an DOM element that doesn't exist in the DOM at the time of load. 基本上,您正在尝试将事件附加到加载时DOM中不存在的DOM元素。 Rewrite the .click() handler too: 同样重写.click()处理程序:

$(document).on('click', '.trashYes', function () {
    $(this).remove();
});

Fiddle: http://jsfiddle.net/6bBU4/ 小提琴: http //jsfiddle.net/6bBU4/

What it's doing is that, it's attaching the .click() event to the document (The top most DOM element) will travel down to find any new .trashYes , thus successfully executing the .remove() . 它正在做的是,它将.click()事件附加到document (最顶层的DOM元素)将向下移动以找到任何新的.trashYes ,从而成功执行.remove() This doesn't have to be bound to the document but to any DOM element within the document as well at load. 这不必绑定到document而是绑定到document中的任何DOM元素以及加载时。

No need to get the id and then try and find it again, just do this... 不需要获取id然后尝试再次找到它,就这样做...

$('<div id="'+id+'" class="keyword-entry" style="z-index:0">'+ui.item.value+'   <--I want to remove this</div>')
    .appendTo($('#keyword-list'))
    .click(function(e){
        $(this).remove();
    });

when adding the keyword entry 添加关键字条目时

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

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