實現手動拖動html table中的行(tr)進行排序.
HTML
需要引入jquery和jquery ui的js文件
<table id="sort" class="grid" title="Kurt Vonnegut novels"> <thead> <tr><th class="index">No.</th><th>Year</th><th>Title</th><th>Grade</th></tr> </thead> <tbody> <tr><td class="index">1</td><td>1969</td><td>Slaughterhouse-Five</td><td>A+</td></tr> <tr><td class="index">2</td><td>1952</td><td>Player Piano</td><td>B</td></tr> <tr><td class="index">3</td><td>1963</td><td>Cat's Cradle</td><td>A+</td></tr> <tr><td class="index">4</td><td>1973</td><td>Breakfast of Champions</td><td>C</td></tr> <tr><td class="index">5</td><td>1965</td><td>God Bless You, Mr. Rosewater</td><td>A</td></tr> </tbody> </table>
javascript:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
var fixHelperModified
= function (e,
tr) { var $originals
= tr.children(); var $helper
= tr.clone(); $helper.children().each( function (index)
{ $( this ).width($originals.eq(index).width()) }); return $helper; }, updateIndex
= function (e,
ui) { $( 'td.index' ,
ui.item.parent()).each( function (i)
{ $( this ).html(i
+ 1); }); }; $( "#sort
tbody" ).sortable({ helper:
fixHelperModified, stop:
updateIndex }).disableSelection(); |
其實只需要$("#sort tbody").sortable().disableSelection();就可以了,那麼那兩個回調函數作用是什麼呢?
helper: fixHelperModified,這個函數的作用是:克隆你正在拖動的tr,然後依次設置你克隆的那個tr的td的寬度,使之拖動時的寬度與原來一致。也就是說,不回調這個函數也可以,就是拖動的時候tr中的單元格寬度會變小。當然了不影響放手後的寬度。
stop: updateIndex,這個函數的作用是,拖動後維護現在索引(即第一列的值)。
參考鏈接:
http://stackoverflow.com/questions/2072848/reorder-html-table-rows-using-drag-and-drop