2015-01-06 39 views
0

我想基於元素的頂部位置。要改變自定義屬性更改自定義屬性基於頂部位置

<div class="wrapper"> 
<div class="class" customAttribute="2" top="600"></div> 
<div class="class" customAttribute="1" top="500"></div> 
<div class="class" customAttribute="4" top="200"></div> 
<div class="class" customAttribute="3" top="400"></div> 
<div class="class" customAttribute="6" top="300"></div> 
<div class="class" customAttribute="5" top="100"></div> 
</div> 
for (var i = 0; i < 6; i++) { 

var firstChild = // gets the customAttribute of the child with the lowest position top value; 

    $('.wrapper:nth-child(firstchild)').attr('customAttribute', i); 
} 

此外,還有將在年底超過6點的div所以它需要是程序性的。謝謝。

+0

你爲什麼不使用真正的自定義數據屬性? 'data-' – j08691

+0

這不是實際的屬性,它只是一個沒有數據的例子。 – pauld

+0

根據'top'對它進行排序,然後設置'customAttribute',你有什麼特別的嘗試? – beautifulcoder

回答

3

這將調整customattribute,就像你要求:

var obj_arr = [];//We will push objects into this array and sort them 
var div_obj_arr = $('.wrapper > div'); 

//iterate through div_obj_arr 
div_obj_arr.each(function(i){ 

    //Push an object into "obj_arr" 
    obj_arr.push({ 
     idx:i,//pre-sorted index of the html elements 
     top:$(this).attr('top')//"top" attribute values 
    }) 
}) 

//sort the object array 
//this ".sort(" will iterate through "obj_arr" 
//and sort them based on the "top" value 
obj_arr = obj_arr.sort(function(a,b){return a.top < b.top ? -1 : 1}); 

//iterate through the newly sorted array of objects 
//and assigns the new attribute values 
$.each(obj_arr,function(i){ 
    divs.eq(this.idx).attr('customattribute',i); 
}); 
+0

也許你應該更多地評論一下代碼,或者基本解釋你所做的事 – sodawillow

+0

你絕對是對的!更好的評論應該是我的新年決議。 :) – JayB

+0

哇。這是冗長的。 :) – sodawillow