2012-07-25 99 views
0

可能重複:
How to sort LI's based on their ID排序圖像通過他們的ID

我有一個動態填充了各種圖像和看起來像一個div:

<div id="images"> 
<img id="img1" src="..." /> 
<img id="img3" src="..." /> 
<img id="img2" src="..." /> 
<img id="img6" src="..." /> 
<img id="img5" src="..." /> 
<img id="img4" src="..." /> 
</div> 

使用JavaScript和jQuery,我需要將圖像排序爲ID的順序,但我很掙扎。繼承人我到目前爲止:

var toSort = $('#images').children; 
toSort = Array.prototype.slice.call(toSort,0); 


toSort.sort(function(a,b){ 
    var aord = +a.id.substr(6); 
    var bord = +b.id.substr(6); 
    return aord - bord; 
}); 


var parent = $('#images'); 
parent.innerHTML=""; 
for(var i=0, l = toSort.length; i<l; ++i){ 
    parent.appendChild(toSort[i]); 
} 

我有多接近?我究竟做錯了什麼?多謝你們。

+0

您的代碼有問題嗎? – 2012-07-25 13:51:34

回答

3
var imgs = $('#images img'); 
imgs.sort(function(a, b) { 
    return a.id > b.id; 
}); 
$('#images').html(imgs); 
​ 

DEMO

OR

var imgs = $('#images img'); 
imgs.sort(function(a, b) { 
    return +a.id.replace('img','') - +b.id.replace('img',''); 
}); 
$('#images').html(imgs); 

DEMO

版與您的代碼:

var parent = $('#images'), 
    children = parent.children(), 
    toSort = Array.prototype.slice.call(children, 0); 

parent[0].innerHTML = ""; //or parent.empty(); 

toSort.sort(function(a, b) { 
    var aord = +a.id.substr(3); 
    var bord = +b.id.substr(3); 
    return aord - bord; 
}); 

for (var i = 0; i < toSort.length; i++) { 
    parent.append(toSort[i]); 
} 

DEMO

+1

'.sort'回調應該返回一個整數('<0','0'或'> 0'),而不是布爾值。 – 2012-07-25 13:53:46

+0

或者你可以使用return(a.id> b.id)? 1:(a.id r3bel 2012-07-25 14:05:15

+0

我試過使用底部的例子,但我得到的錯誤「對象不支持屬性或方法'排序'」?任何想法爲什麼? – user1055650 2012-07-25 14:08:56

0
var elem = $('#images'), 
    imgs = elem.find('img'); 
imgs.sort(function(a, b) { 
    return a.id.toUpperCase().localeCompare(b.id.toUpperCase()); 
}); 
$.each(imgs, function(idx, itm) { elem.append(itm); }); 

FIDDLE

0

我覺得@thecodeparadox版本更好,但這裏是你的代碼糾正一點點。我將img改爲跨度以使其更加明顯。

http://jsfiddle.net/whnyn/