2013-02-07 73 views
2

假设我有一个有很多有序元素的集合,那么插入另一个新子对象的常用方法是什么?抽象订单位置JavaScript插入位置

使用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个元素。

+0

使用'的.index()',而不是'。数据(“orderPosition ')'..但这只是等于'$(new)'不是吗? –

+0

是的,会的。我已经更新了?ion – mate64

+0

您是否已经有了对元素进行排序的代码(在插入任何内容之前)? – Bergi

回答

3

我认为使用整数数组可能是最有效的方法。您可以在阵列中保持有序元素的恒定名单的地方(甚至继续整理需要的话):

//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); 

http://jsfiddle.net/ExplosionPIlls/ULEFX/

+0

+1使用'dataset' – Bergi

+0

+1我需要一些药片...... – mate64

0

为什么不直接在数组中存储顺序位置,然后使用它计算索引?这是更好的解决方案,因为阅读DOM属性消耗更多的CPU比循环通过阵列和比较你的新项目与现有的