2011-12-30 98 views
2

如何将listitemssortList[0]sortList[1]排序?

例如:http://jsfiddle.net/wmaqb/20/Jquery可排序 - 排序列表手册

HTML

<div id="sortable">   
    <div id="sort_18b0c79408a72">Berlin</div> 
    <div id="sort_dkj8das9sd98a">Munich</div> 
    <div id="sort_skd887f987sad">Browntown</div> 
    <div id="sort_54asdliöldawf">Halle</div> 
    <div id="sort_f5456sdfefsdf">Hamburg</div>  
</div> 

<input id="sortList0Bt" type="button" value="sortList0" /> 
<input id="sortList1Bt" type="button" value="sortList1" /> 

JS

sortList= new Array(); 

sortList[0] = {}; 
sortList[0]['18b0c79408a72'] = 6; 
sortList[0]['dkj8das9sd98a'] = 9; 
sortList[0]['skd887f987sad'] = 3; 
sortList[0]['54asdliöldawf'] = 1; 
sortList[0]['f5456sdfefsdf'] = 5; 

sortList[1] = {};  
sortList[1]['18b0c79408a72'] = 1; 
sortList[1]['dkj8das9sd98a'] = 2; 
sortList[1]['skd887f987sad'] = 3; 
sortList[1]['54asdliöldawf'] = 4; 
sortList[1]['f5456sdfefsdf'] = 5; 

$("#sortable").sortable(); 

$('#sortList0Bt').click(function() { sortIt(sortList[0]); }); 
$('#sortList1Bt').click(function() { sortIt(sortList[1]); }); 

JS - 排序功能

function sortIt(sortList) 
{ 
    var mylist = $('#sortable'); 
    var listitems = mylist.children('div').get(); 

    listitems.sort(function(a, b) 
    { 
     // --------------- >>> HERE <<< -------------- 
    }); 

    $.each(listitems, function(idx, itm) { mylist.append(itm); }); 
} 

在此先感谢!

回答

1

基本上你想要多个按钮以不同的方式对同一个列表进行排序,如果我理解正确的话?

我建议改变如下:

<input id="sortList0Bt" class="sortbutton" type="button" value="sortList0" /> 
<input id="sortList1Bt" class="sortbutton" type="button" value="sortList1" /> 

$('.sortbutton').click(function() { 
    var id = parseInt($(this).val().replace("sortList","")); 
    //The above gives you "0" or "1" which is then parsed to an int 
    sortIt(sortList[id]); 
}); 

现在你没有任何点击处理硬编码,只有按钮本身。

像你这样手动创建排序数组似乎效率不高。我不确定在使用.sortable()或div ID(这些ID本身并没有使它更清晰)时有多少自由,但我会建议通过类或在div中添加一个元素来完成此功能,可以用来订购它们。

例如为:

<div id="sort_18b0c79408a72"> 
    Berlin 
    <input type="hidden" class="sort_me_for_button_0" id="0_1"> 
    <input type="hidden" class="sort_me_for_button_1" id="1_4"> 
</div> 

如果按钮0被点击时,该元素将被显示在第1位。如果点击按钮1,该元素将显示在第4位。 完全写作需要一定的脑力,但我认为这是处理这个问题的最有效和最清晰的方法。

给你,你会如何对它们进行排序的想法:

<div id="mysortedlist"></div> 

function sortIt(id) { //not the sortList, just the 0 or 1 int we parsed earlier. 
    var number_of_items = $(".sort_me_for_button_"+id).length; //Now we know how many items there are to sort. 

    for (int i = 1; i < number_of_items + 1; i++) { 
     $("#mysortedlist").append($("#" + id + "_" + i).parent()); //the parent() is the div in which the hidden field resides. 
    }; 

    $("#sortable").html($("#mysortedlist").html()); 
}