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