2013-02-07 78 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比循環通過陣列和比較你的新項目與現有的