假设我有一个包含一堆有序元素的集合,那么在其抽象顺序位置处插入另一个新子元素的常用方法是什么?
使用 dom 库 $(new).eq($(new).data('orderPosition'));
不起作用,因为它不是有效的索引。
// Add this element to it's logic position in the collection:
<div data-order-position="10"></div>
// The collection
<div id="myCollection">
<div data-order-position="4"></div>
<div data-order-position="67"></div>
<div data-order-position="81"></div>
<div data-order-position="82"></div>
<div data-order-position="761"></div>
</div>
我的真实收藏包含大约 400 个元素。
最佳答案
我认为使用整数数组可能是最有效的方法。您可以在数组中的某个位置维护已排序元素的常量列表(甚至可以根据需要继续排序):
//Array of positions
var positions = [];
//Initially set up the array in question
//divs are already sorted, as we know
$("#myCollection div").each(function () {
positions.push(parseInt(this.dataset.orderPosition));
});
//Create the new node we want to insert (in your case it may already exist)
var $new = $("<div>").data('order-position', 10).text(10);
//Append the new node index (if node already exists, just use `.data` as above)
positions.push(10);
//Yes, for whatever reason JS sorts by string and not number by default.
//There may also be a more efficient way to add the integer in the correct spot
//without having to sort all over again, but this is fast enough
positions.sort(function (a, b) {
return a - b;
});
//Insert the new node!
$("#myCollection div").eq(positions.indexOf(10) - 1).after($new);
关于JavaScript insertAt 位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14762613/