參考原文連接:javascript
http://stackoverflow.com/questions/2072848/reorder-html-table-rows-using-drag-and-drophtml
在最近的項目中,咱們有這樣一個需求,要手動拖動html table中的行(tr)進行排序,java
就是我能夠將第一行拖到第三行,第四行拖到六行這樣子。jquery
一開始我想起了jquery ui中的sortable,發現沒有這樣的例子。less
束手無策,因而谷歌之,發現了這位大神的回覆。原來人家仍是用了jquery ui的sortable函數
HTMLui
須要引入jquery和jquery ui的js文件this
<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:spa
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();就能夠了,那麼那兩個回調函數做用是什麼呢?.net
helper: fixHelperModified,這個函數的做用是:克隆你正在拖動的tr,而後依次設置你克隆的那個tr的td的寬度,使之拖動時的寬度與原來一致。也就是說,不回調這個函數也能夠,就是拖動的時候tr中的單元格寬度會變小。固然了不影響放手後的寬度。
stop: updateIndex,這個函數的做用是,拖動後維護如今索引(即第一列的值)。
原文demo地址:http://jsfiddle.net/pmw57/tzYbU/205/