如何重新排序表行?

<table class="table table-bordered" style="text-align: center; width: 95%;">
    <tr>
        <td style="width: 2%;"></td>
        <td>Prekės pavadinimas</td>
        <td style="width: 15%;">Kiekis</td>
        <td style="width: 15%;">Kaina</td>
        <td style="width: 15%;">Suma</td>
        <td style="width: 2%;"></td>
    </tr>
    <tr>
        <td style="vertical-align: middle;">
            <span class="glyphicon glyphicon-menu-up"></span><br>
            <span class="glyphicon glyphicon-menu-down"></span>
        </td>
        <td style="vertical-align: middle;">
            <div class="form-group">
                <label for="product"></label>
                <input type="text" class="form-control" id="product" name="product" placeholder="Prekė">
            </div>
        </td>
        <td style="vertical-align: middle;">
            <div class="form-group">
                <label for="quantity"></label>
                <input type="text" class="form-control" id="quantity" name="quantity" placeholder="Kiekis">
            </div>
        </td>
        <td style="vertical-align: middle;">
            <div class="form-group">
                <label for="price"></label>
                <input type="text" class="form-control" id="price" name="price" placeholder="Kaina">
            </div>
        </td>
        <td style="vertical-align: middle;">
            <div class="form-group">
                <label for="total"></label>
                <input type="text" class="form-control" id="total" name="total" placeholder="Suma" disabled>
            </div>
        </td>
        <td style="vertical-align: middle;"><a href="#"><span class="glyphicon glyphicon-remove" style="color: red;"></span></a></td>
    </tr>
</table>

$('tr td span:nth-of-type(1)').on('click', function() {
    moveup = $(this).parent();
    moveup.prev().before(moveup);
});

$('tr td span:nth-of-type(2)').on('click', function() {
    movedown = $(this).parent();
    movedown.next().after(movedown);
});

下面是我的代码如何使用jQuery:
http://jsfiddle.net/zJ8hd/21/
提前谢谢你的帮助!:)

最佳答案

您遍历和修改DOM的逻辑不太正确。您需要获取父元素,然后在prev/nexttr之前/之后插入它,如下所示:

$('tr td span:nth-of-type(1)').on('click', function() {
    var $row = $(this).closest('tr')
    if ($row.index() == 1)
        return;
    $row.insertBefore($row.prev());
});

$('tr td span:nth-of-type(2)').on('click', function() {
    var $row = $(this).closest('tr')
    $row.insertAfter($row.next());
});

Working example
注:我在小提琴中添加了trfoo作为默认字段值,只是为了使移动更加明显。

09-12 02:08