通过拖动表格行进行行排序

参考原文链接:

http://stackoverflow.com/questions/2072848/reorder-html-table-rows-using-drag-and-drop

在最近的项目中,我们有这样一个需求,要手动拖动html table中的行(tr)进行排序,

就是我可以将第一行拖到第三行,第四行拖到六行这样子。

一开始我想起了jquery ui中的sortable,发现没有这样的例子。

一筹莫展,于是谷歌之,发现了这位大神的回复。原来人家还是用了jquery ui的sortable

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:

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/

  

原文地址:https://www.cnblogs.com/haitao-fan/p/3908633.html