2011-12-09 35 views
3

我正在尝试使用jQuery对div进行排序。从本质上讲列表可能是这样的:根据div标签和jQuery中的数字对div进行排序

<div class="contest_entry"><img src="image.png" /><span class="votes">14</span></div> 
<div class="contest_entry"><img src="image.png" /><span class="votes">8</span></div> 
<div class="contest_entry"><img src="image.png" /><span class="votes">2</span></div> 
<div class="contest_entry"><img src="image.png" /><span class="votes">2</span></div> 
<div class="contest_entry"><img src="image.png" /><span class="votes">2</span></div> 
<div class="contest_entry"><img src="image.png" /><span class="votes">21</span></div> 

我试图用一些jQuery的通过次数最多的div自动排序到最低。我怎么能解决这个问题?感谢任何方向!猜猜我应该补充说,排序应该发生在页面加载。 :)

+0

您的问题与此相关:http://stackoverflow.com/questions/8433691/sorting-list-of-elements-in-jquery/8434126#8434 126 – epignosisx

回答

11

我为此写了一个small plugin。随意偷。 基本上,您选择元素,对它们进行排序,然后以新顺序重新添加。

============================================== ================================

每杰森的请求包括代码在这里

$(".contest_entry").orderBy(function() {return +$(this).text();}).appendTo("#parent_div"); 

#parent_div.contest_entry的容器。

+只是一个偷偷摸摸的方式来将值转换为数字比较而不是字符串比较(除非这是你想要的)。

orderBy()是我写的排序插件。我扩大了它安静一点从那时起,但这里是一个简单的版本:

jQuery.fn.orderBy = function(keySelector) 
{ 
    return this.sort(function(a,b) 
    { 
     a = keySelector.apply(a); 
     b = keySelector.apply(b); 
     if (a > b) 
      return 1; 
     if (a < b) 
      return -1; 
     return 0; 
    }); 
}; 
+0

+1 nicely @ liho1eye。但是,您应该在答案中包含代码,以防止链接停止工作并且更容易引用。 –

+0

谢谢。太棒了。像魅力一样工作! –

0

沿着这些线路的一些事情应该工作:

var list = []; 

function sortDivs(a,b) 
{ 
    return parseInt(a.text(), 10) - parseInt(b.text(), 10); 
} 

$('contest_entry').each(function() { 
    list.push(this); 
    $(this).detach(); 
}) 

list.sort(sortDivs) 

for (var x = 0; x < list.length; x++) { 
    $('#parent_el').append(list[x]);//where parent_el is the place you want to reinsert the divs in the DOM 
} 
0
$(function(){ 
    var sortedList = $('.contest_entry').toArray().sort(function(lhs, rhs){ 
     return parseInt($(rhs).children("span.votes").text(),10) - parseInt($(lhs).children("span.votes").text(),10); 
    }); 
    //the variable 'sortedList' holds the divs ordered. All you need to do is place them in the DOM. 
}); 

这里是一个工作示例:http://jsfiddle.net/ZCvUa/

+0

供参考:jQuery对象从数组中直接窃取它的排序方法,所以不需要来回转换它。 –

0
var jVotes = $('div.contest_entry span.votes'), vals = []; 
jVotes.each(function() { 
    var numVotes = $(this).html(); // may also be able to use .text() 
    vals.push(numVotes); 
    $(this).data('num-votes', numVotes); 
}); 
vals.sort(function(a, b) { 
    return (a < b) ? -1 : (a > b) ? 1 : 0; 
}); 
var jParent = $('selector for parent container'); 
for (var i = 0; i < jVotes.length; i++) { 
    jParent.append(jParent.find('[data-num-votes=' + vals[i] + ']')); 
} 
相关问题