我想根据元素的顶部位置更改自定义属性..
<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 :(得分: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);
});