javascript - jquery `append()` 是否删除重复对象?

标签 javascript jquery

我正在使用 jQuery 对表格进行排序,大致遵循找到的代码 here .代码示意图如下:

$('.sort-table').click(function(e) {
    // cache objects
    $table  = $('#sort-table'),        // cache the target table DOM element
    $rows   = $('tbody > tr', $table); // cache rows from target table body

    // sort items
    $rows.sort(<my_predicate_function(a,b){...}>);

    // assign to table - what is going on?
    $rows.each(function(index, row){
        $table.append(row);  // <-- how come $table remains the same size?                  
    });
});

虽然代码工作正常,但我对将行追加回表的代码感到困惑,它只是迭代排序的行,将每个追加到 $table 的末尾。< br/>
我们在任何阶段都没有从它之前的 child 中清空 $table

  • 既然 $table 从未被清空,为什么 $table 保持相同的大小?
  • append() 是否也在目标容器中强制执行唯一性?

最佳答案

这就是 DOM 的工作原理。你不能在两个不同的地方有一个元素。如果一个元素已经在文档中,而您将它放在其他地方,它将从当前位置移动。我想,它有点像 Set,但它不是指定的方式。所以它不会删除重复的对象,因为永远不会有重复的对象:它只是移动同一个对象,它只能存在于一个地方。

来自 the MDN documentation for the underlying method, Node.appendChild :

The Node.appendChild() method adds a node to the end of the list of children of a specified parent node. If the given child is a reference to an existing node in the document, appendChild() moves it from its current position to the new position (there is no requirement to remove the node from its parent node before appending it to some other node).

如果你想复制元素,你需要克隆它们( DOM , jQuery )。

关于javascript - jquery `append()` 是否删除重复对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40909467/

相关文章:

javascript - 绑定(bind)网页上的内部链接以动态加载,而不会增加分析跳出率

javascript - 如何在 Angular js 中的 .run 方法内调用读取 json 文件的工厂?是否可能?

javascript - AngularJS 1.5 中的组件不监听来自 $scope 的广播事件

javascript - jvectormap 合并两个 map

jquery - Parseerror 使用 ajax 将数据推送到 python 脚本

javascript - 使用单个 JavaScript 上下文运行两个 Electron 窗口

清理 CSS 的 Javascript 解决方案

jquery - 如何使用 jQuery 获取 div 的当前类?

javascript - 组合多个 Ajax 加载函数

javascript - 为什么 "_=1389258551926"在 ajax 请求中作为查询字符串参数发送?