有些时候我们需要随意拖动表格的一行,进行简单的排序,这里就介绍一种只需要js和jquery就能实现的一种方式:
需要引入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 style="cursor:pointer"><td class="index">1</td><td>1969</td><td>Slaughterhouse-Five</td><td>A+</td></tr>
<tr style="cursor:pointer"><td class="index">2</td><td>1952</td><td>Player Piano</td><td>B</td></tr>
<tr style="cursor:pointer"><td class="index">3</td><td>1963</td><td>Cat's Cradle</td><td>A+</td></tr>
<tr style="cursor:pointer"><td class="index">4</td><td>1973</td><td>Breakfast of Champions</td><td>C</td></tr>
<tr style="cursor:pointer"><td class="index">5</td><td>1965</td><td>God Bless You, Mr. Rosewater</td><td>A</td></tr>
</tbody>
</table>
js代码:
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,这个函数的作用是,拖动后维护现在索引(即第一列的值)。
原文demo地址:http://jsfiddle.net/pmw57/tzYbU/205/ (原demo没有加入style="cursor:pointer"
,所以拖动的时候会是输入符号,加上这个就会变成手指)