利用jquery ui实现表格行排序

利用jquery ui排序

通过上下拖动表格行进行手动排序,使其排序号自动更新

表格大致如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
<table >
<thead>
<tr>
<th style="width:10px" >移动手柄</th>
<th style="width:50px">位置序号</th>
...
</tr>
</thead>
<tbody id="sortable">
<tr sort_handle="1" >
<td class="myhandle"> = </td>
<td>
<input class="sort_id" type="hidden" name="" value="5" readonly="readonly">
</td>
</tr>
...
<tr sort_handle="2" >
<td class="myhandle"> = </td>
<td>
<input class="sort_id" type="hidden" name="" value="6" readonly="readonly">
</td>
</tr>
...
</table>

用到的主要配置项:

sort(event,ui) 排序时触发,ui.item:代表当前被拖动元素的jquery对象;

update(event,ui) 当用户停止排序并且DOM元素的位置改变后触发。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
<script type="text/javascript">   
//UI修改
var fixHelper = function(e, ui) {
ui.children().each(function() {
$(this).width($(this).width()); //拖动时设置拖动行单元格宽度,否则会收缩
});
return ui;
};
//排序
$(function() {
$( "#sortable").sortable({
handle:".myhandle",//拖动手柄,跟页面元素对应
cursor: "move",
helper: fixHelper, //调用fixHelper
axis:"y",//移动方向
grid:[300,5],//移动位移量限制: x,y
containment:"document",//移动范围
opacity:0.8,//透明度
start:function(e, ui){
ui.helper.css({"background":"#aaa"});//设置被拖动的元素背景色 //拖动时的行,要用ui.helper
return ui;
},
update:function(e,ui){
//当前元素
var selected_item = ui.item;
var selected_sort_id = selected_item.find('.sort_id').val();
selected_sort_id = parseInt(selected_sort_id);

//放置位置的下一个元素
var placed_next_item = selected_item.next('tr');
var placed_next_sort_id = placed_next_item.find('.sort_id').val();
placed_next_sort_id = parseInt(placed_next_sort_id);

var tr,new_sort_id,i,changed_count;
//向上移动
if(selected_sort_id>placed_next_sort_id){

changed_count = selected_sort_id - placed_next_sort_id;//(除被拖动的元素外)排序值发生改变的元素数
//更新排序值
tr=placed_next_item;
new_sort_id = placed_next_sort_id+1;
for(i=1;i<=changed_count;i++){
tr.find('.sort_id').attr('value',new_sort_id);
tr = tr.next();
new_sort_id++;
}
selected_item.find('.sort_id').attr('value',placed_next_sort_id);//改变当前移动元素的排序值
}else{//向下移动

//放置位置的上一个元素
var placed_prev_item = selected_item.prev('tr');
var placed_prev_sort_id = placed_prev_item.find('.sort_id').val();
placed_prev_sort_id = parseInt(placed_prev_sort_id);

changed_count = placed_prev_sort_id-selected_sort_id;
tr = placed_prev_item;
new_sort_id = placed_prev_sort_id-1;
for(i=1;i<=changed_count;i++){
tr.find('.sort_id').attr('value',new_sort_id);
tr = tr.prev();
new_sort_id--;
}
selected_item.find('.sort_id').attr('value',placed_prev_sort_id);//改变当前移动元素的排序值
}
},
//stop:function(e, ui){
// ui.item.removeClass("ui-state-highlight"); //释放鼠标时,要用ui.item才是释放的行
// return ui;
//},
});
});
</script>