jQuery .remove() 不会删除元素

jQuery .remove() won't remove element

我正在尝试从 HTML 页面动态删除 li 元素,我使用的是 .remove() 方法,但是,如果我检查 HTML 页面我可以看到该元素未被删除,它只是将他的可见性更改为 display: none;。 有什么方法可以明确地从页面中删除该元素?

这是片段(我从 #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);
        }

    }
});

使用slideUp的"complete"回调函数 ( http://api.jquery.com/slideup/ )

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

这不起作用的原因是因为您在 setTimeout 子函数内调用 $(this)。您需要将元素定义为变量才能在子函数中访问它。

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

    }
});

或听从 andi 的建议并使用 .sideUp() 的回调选项:

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