2017-03-10 28 views
1

我需要您的帮助,我正在工作。我创建了一个HTML表,其中有7个类别(7 tr's)。每个tr有2个td's,一个是类别名称,另一个是输入复选框。因此,如果用户选择例如1,3,7(第一类复选框,第三类复选框等),将会创建一个javascript数组,如order = [1, 3, 7];使用jQuery根据订单数组重新排序表的表格tr

所以我希望(在页面重新加载时)使用jQuery脚本将这些选定的tr移动到表顶部。

HTML表:

<tbody id="news_body"> 
<tr id="1"> 
<td class="categories">World</td> 
<td class="category_enabled" style="float: right;"><input type="checkbox" value="1"/></td> 
</tr> 

<tr id="2"> 
<td class="categories">Sports</td> 
<td class="category_enabled" style="float: right;"><input type="checkbox" value="2"/></td>  
</tr> 
. 
. 
. 
<tr id="7"> 
<td class="categories">Economy</td> 
<td class="category_enabled" style="float: right;"><input type="checkbox" value="7"/></td>  
</tr> 
</tbody> 

我已经尝试过这一点,但tr的显示表的底部:

var order = [1, 3, 7]; 
$.each(order, function(){ 
    $("#news_body").append($("#" + this)); 
}) 

任何想法会有所帮助..

解决方案(更新):

$.each(categories, function(){ 
    $("#news_table").append($("#" + this)); 
}) 

回答

1

试试这个中庸

jQuery(document).ready(function($) { 

var order = [1, 3, 7]; 
reverse_order=order.reverse();// reversing array so when prepending, checkboxes will display in right order 
$.each(reverse_order, function(key,value){ 

    var selected=$("#" + value);// keep the original tr 
    $("#" + value).remove();// remove from table 
    $("#news_body").prepend(selected);// then prepend it 
}) 
+0

感谢您的回答! – GeoDim

+0

欢迎您 –

1

你想使用的是prepend()。 这会将elem插入表格的开头。

var order = [1, 3, 7]; 
$.each(order, function(index, value){ 
    $("#news_body").prepend($("#" + this)); 
}) 
+0

感谢您再寄一次相信我找到了解决办法! – GeoDim

相关问题