js拖动table行tr排序

来源:互联网 发布:海康网络键盘 编辑:程序博客网 时间:2024/05/22 17:42

实现手动拖动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


0 0