简体   繁体   English

jQuery .remove()不会删除元素

[英]jQuery .remove() won't remove element

I'm trying to dynamically remove li elements from an HTML page, I'm using the .remove() method but, if I inspect the HTML page I can see that the element is NOT removed, it has simply changed his visibility to display: none; 我正在尝试从HTML页面中动态删除li元素,正在使用.remove()方法,但是,如果我检查HTML页面,我可以看到该元素没有被删除,它只是改变了其display: none;可见性display: none; . Is there a way I can DEFINITIVELY remove the element from the page? 有没有办法我可以确定地从页面中删除元素?

this is the snippet (I clone a li from #ul1 and append it to #ul2 ): 这是代码段(我从#ul1克隆了一个li并将其附加到#ul2 ):

var oggettoClone = $(this).clone();
oggettoClone.appendTo("#ul2");

$(oggettoClone).bind({
    click: function(o) {

        var r = confirm("Remove this element?");
        if (r == true) 
        {
            $(this).slideUp();

            setTimeout(function(){
                $(this).remove();
            }, 2000);
        }

    }
});

Use the "complete" callback function of slideUp ( http://api.jquery.com/slideup/ ) 使用slideUp的“完成”回调函数( http://api.jquery.com/slideup/

$(this).slideUp(function(){
    // this part will execute when slideUp is complete.
    $(this).remove();
});

The reason this doesn't work is because you are calling $(this) inside the setTimeout sub-function. 这不起作用的原因是因为您正在setTimeout子函数内调用$(this) You need to define the element as a variable to access it inside a sub-function. 您需要将元素定义为变量才能在子函数中访问它。

$(oggettoClone).bind({
    click: function(o) {
        var r = confirm("Remove this element?");
        var t = $(this);
        if (r == true) {
            $(t).slideUp();
            setTimeout(function(){
                $(t).remove();
            }, 2000);
        }

    }
});

or follow andi's advice and use .sideUp() 's callback option: 或遵循andi的建议并使用.sideUp()的回调选项:

$(oggettoClone).bind({
    click: function(o) {
        var r = confirm("Remove this element?");
        if (r == true) {
            $(this).slideUp(function(){
                $(this).remove();
            });
        }
    }
});

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

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