删除动态创建的页面元素

Removing dynamically created page elements

本文关键字:元素 动态 创建 删除      更新时间:2023-09-26

在这里查看小提琴中的行为。

$(document).ready(function () {
            $('.tile').draggable();
            $('.tile').on('dragstart', function () {
                var numClones = $('.tile').length - 1
                if (numClones > 0) {
                    //why can't I use fadeOut or empty here?
                    //make sure we don't remove the clone before it's made
                    $('.tile')[numClones].remove();
                }
                console.log(numClones);
                var clone = $(this).clone();
                clone.appendTo('body');
            });
        });

这允许用户在拖动事件上创建页面元素的克隆。 它还会删除以前的克隆。 在上面的注释行中,为什么当我尝试使用 fadeOut 从页面中删除div 时出现错误? 这是一个jQuery对象,对吧? 我收到错误Object #<HTMLDivElement has no method fadeOut

jQuery元素的索引访问器(这是get(index)的简写)返回DOM元素。你正在寻找jQuery元素,在这种情况下你应该使用.eq(index)(这个没有简写)。

remove()工作的唯一原因是因为它也是一个 DOM 元素方法。

$('.tile').eq(numClones).fadeOut(function () {
    // make sure the old clones get deleted, not just hidden
    $(this).remove();   
});

http://jsfiddle.net/2rnSk/1/

试试这个:

$($('.tile')[numClones]).fadeOut();

jQuery 对象伪装成其选择器匹配的元素数组。当您应用索引时,您返回的是一个HTMLDivElement。但是,如果您将其包装在jQuery对象中,则应该能够毫无问题地应用fadeOut