如何使用jquery sortable选择多行并在同一个表中对它们进行排序

时间:2014-02-28 06:02:13

标签: jquery

<table>
    <tbody>
        <tr>
            <th>Header1</th>
            <th>Header2</th>
            <th>Header3</th>
        </tr>
        <tr>
            <td>Data1</td>
            <td>Data2</td>
            <td>Data3</td>
        </tr>
        <tr>
            <td>Data4</td>
            <td>Data5</td>
            <td>Data6</td>
        </tr>
        <tr>
            <td>Data7</td>
            <td>Data8</td>
            <td>Data9</td>
        </tr>
        <tr>
            <td>Data10</td>
            <td>Data11</td>
            <td>Data12</td>
        </tr>
        <tr>
            <td>Data13</td>
            <td>Data14</td>
            <td>Data15</td>
        </tr> 
    </tbody>
</table>

$(function() {
    $('table tbody').sortable({
        items: 'tr:not(tr:first-child)',
        cursor: 'move',
        connectWith: 'table',
        axis: 'y',
        dropOnEmpty: true
    });

    $('table tr').on('click', function () {
        $(this).toggleClass('selectedRow');
    });
});


table tbody{
    background-color: greenYellow;
}


table tbody th{
    background-color: green;
}

.selectedRow{
    background-color: #abcdef;
}

Fiddle Here

如何通过插入在特定行索引处选择的行来对表进行排序。

1 个答案:

答案 0 :(得分:7)

得到答案:

$('table tbody').on('click', 'tr', function(e){
    if(e.ctrlKey || e.metaKey){
        $(this).toggleClass('selected');
    }else{
        $(this).addClass('selected').siblings().removeClass('selected');
    }
}).sortable({
    items: 'tr:not(tr:first-child)',
    connectWith: 'table',
    cursor: 'move',
    delay: 150,
    revert: 0,
    helper: function(e, item){
        if(!item.hasClass('selected')){
           item.addClass('selected').siblings().removeClass('selected');
        }

        var elements = item.parent().children('.selected').clone();
        item.data('multidrag', elements).siblings('.selected').remove();

        var helper = $('<tr/>');
        return helper.append(elements);
    },
    stop: function(e, ui){
        var elements = ui.item.data('multidrag');
        ui.item.after(elements).remove();
    }
});


table tbody{
    background-color: greenYellow;
}


table tbody th{
    background-color: green;
}

.selected{
    background-color: Azure;
}

Updated Fiddle Here