JavaScript插入位置

JavaScript插入位置,javascript,jquery,indexing,append,Javascript,Jquery,Indexing,Append,假设我有一个包含大量有序元素的集合,在它的抽象顺序位置插入另一个子元素的常用方法是什么 使用dom库$(新).eq($(新).data('orderPosition')无效,因为它不是有效的索引 // Add this element to it's logic position in the collection: <div data-order-position="10"></div> // The collection <div id="myCollecti

假设我有一个包含大量有序元素的集合,在它的抽象顺序位置插入另一个子元素的常用方法是什么

使用dom库
$(新).eq($(新).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个元素。

为什么不将订单位置存储在数组中,然后使用它计算索引?这是一个更好的解决方案,因为读取DOM属性比循环遍历数组并将新项与现有项进行比较要耗费更多的CPU。我认为使用整数数组可能是最有效的方法。您可以在某个位置维护数组中已排序元素的常量列表(甚至可以根据需要继续排序):

//位置数组
var头寸=[];
//最初设置有问题的阵列
//正如我们所知,div已经被分类了
$(“#myCollection div”)。每个(函数(){
positions.push(parseInt(this.dataset.orderPosition));
});
//创建要插入的新节点(在您的情况下,它可能已经存在)
var$new=$(“”)。数据('order-position',10)。文本(10);
//追加新的节点索引(如果节点已经存在,只需如上所述使用“.data”)
位置。推(10);
//是的,不管出于什么原因,JS都会按字符串排序,而不是默认的数字。
//还有一种更有效的方法可以将整数添加到正确的位置
//无需重新排序,但这已经足够快了
位置。排序(功能(a、b){
返回a-b;
});
//插入新节点!
美元(“#myCollection div”).eq(positions.indexOf(10)-1)。之后($new);

使用
.index()
而不是
.data('orderPosition')
。。但那就等于
$(新)了,不是吗?是的,是的。我已经更新了?您是否已经有了对元素进行排序的代码(在插入任何内容之前)?集合是从数据库中筛选出来的结果。
//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);