简体   繁体   English

使用jQuery删除DOM元素无法正常工作

[英]Removing a DOM element using jQuery not working

I'll get straight to the point, I am using jQuery to clone a div element, which has a span within it to which I have binded a click event that when triggered removes the just cloned section from the DOM, now the first section works ok, but for some reason it won't remove the cloned sections once they are created, here is my code, 我将直截了当地说,我正在使用jQuery克隆一个div元素,其中包含一个span,我绑定了一个click事件,当触发时从DOM中删除刚刚克隆的部分,现在第一部分工作了好的,但由于某种原因,一旦创建克隆部分就不会删除它们,这是我的代码,

HTML: HTML:

<div id='wrapper'>
<div id="mail">
<div class="container" id="email">
    <label for="email_address">Email address: </label>
    <div>
        <input type="text" name="email_address" id="email_address"  />
        <span class="remove"></span>
    </div>
</div>
</div>
<div class="container">
    <input type="button" id="button" name="button" value="click me" />
</div>
</div>

jQuery: jQuery的:

$(document).ready(function() {

        $("span.remove").click(function(){
            $(this).parents("div.container").remove();
        });


        var count = 0;

        $('#button').attr('disabled','');
        $('#button').click(function(){
            count++;
            alert(count);
            var test = $('#email.container').clone().attr('id', 'email_' + count).appendTo('#mail');
            test.children(':nth-child(2)').children(':first').attr('id', 'mail_' + count);

            if(count == 3){
                $('#button').attr('disabled','disabled');
            }

        });
});

I'm probably missing something small, but I can't seem to find the problem. 我可能错过了一些小事,但我似乎无法找到问题所在。

Also, I've been trying to find a better way of cloning the sections, and a better way of traversing the child elements when I rename them, it seems a little messy at the moment, any ideas on that? 另外,我一直试图找到一种更好的方法来克隆这些部分,并且当我重命名时更好地遍历子元素,目前看起来有点乱,有什么想法吗?

Thanx in advance! Thanx提前!

The problem is as @pharalia stated . 问题是@pharalia说的

A solution is to use .live to bind your handlers: 解决方案是使用.live绑定您的处理程序:

    $("span.remove").live('click', function(){
        $(this).parents("div.container").remove();
    });

DOM events aren't copied along with an element, and you are attaching the event on load. DOM事件不会与元素一起复制,而是在加载时附加事件。 You need to attach the event to the cloned element / children when they are created. 您需要在创建事件时将事件附加到克隆元素/子元素。

you can use .clone(true) there. 你可以在那里使用.clone(true) It will copy also the events binded to the element. 它还会复制绑定到元素的事件。 without true as the parameter, the event is not copied. 如果不将true作为参数,则不会复制事件。

demo 演示

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

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