要對網頁上的標籤進行排序,最簡單的思路可以濃縮成三步:先把標籤用 jQuery 讀進物件陣列,再用 JS 對物件陣列排序,最後用排序好的陣列內容覆蓋回網頁上的標籤。切記不要試圖直接對網頁內容做搬移,一切以「陣列」為操作對象才是正解。
//排序從文字短的到長的
var arr_a = new Array();
var i = 0;
$(".type_list_txt > span:contains('T恤')").parent().children("a").each(function(){
arr_a[i] = $(this).clone();
i++;
});
for(i = 0; i < arr_a.length; i++)
{
for(j = i + 1; j < arr_a.length; j++)
{
if($(arr_a[i]).text().length > $(arr_a[j]).text().length )
{
temp = arr_a[i];
arr_a[i] = arr_a[j];
arr_a[j] = temp;
}
}
}
i = 0;
$(".type_list_txt > span:contains('T恤')").parent().children("a").each(function(){
$(this).replaceWith($(arr_a[i]));
i++;
});
第一段用 each 把符合條件的 a 標籤逐一 clone 進 arr_a 陣列;中間用一個簡單的氣泡排序,比較每個元素 .text().length 的長度並交換位置,達到由短到長的排序;最後再用 each 搭配 replaceWith,把排序後的陣列內容依序覆蓋回原本的標籤位置。
整個流程的關鍵在於「先抽離成資料、排序資料、再寫回畫面」,這樣既清晰又不易出錯,是處理這類 DOM 排序問題的通用套路。