Re-number the id's of table rows using jQuery

|▌冷眼眸甩不掉的悲伤 提交于 2020-01-25 03:22:17

问题


I have the following table code:

<tbody>
    <tr data-id='1' id='item-1'>
        <td>30-01-2014</td>
    </tr>   
    <tr data-id='19' id='item-2'>
        <td>30-01-2014</td>
    </tr>
    <tr data-id='5' id='item-3'>
        <td>30-01-2014</td>
    </tr>
    <tr data-id='39' id='item-4'>
        <td>30-01-2014</td>
    </tr>
</tbody>

and the jQuery:

$('table tbody').sortable({
    axis: 'y',
    update: function (event, ui) {
        var data = $(this).sortable('serialize');
        $.ajax({
            data: data,
            type: 'POST',
            url: 'updatePagesOrder.php'
        });
    }
});
var i = 1;
$('table > tbody  > tr').each(function () {
    $('tr').attr('id', 'item-' + i);
    i++;
});

What I want to do is that after the sortable function executed the id of the items will be ordered again from 1 to 4. I have tried to code above, but it didn't work.

Wish for help...Thanks!


回答1:


No need to declare i you're already using .each() So

try this

$('table > tbody tr').each(function (i) {
     $(this).attr('id', 'item-' + (i + 1)); // use $(this) as a reference to current tr object
});

used (i+1) because index starts from 0

Demo




回答2:


I might not be understanding your question very well, but I believe you want the IDs to update whenever the table rows are reordered?

If that's the case, then I believe the issue is that you are updating the IDs after initializing the sortable plugin, but this change will be overridden when the user reorders the table rows. What you should instead do is update the IDs in the update function. If you want the IDs to be updated after serialization, then place the call to updateRowIDs() after the call to the serialization.

$('table tbody').sortable({
    axis: 'y',
    update: function (event, ui) {
        updateRowIDs();
        var data = $(this).sortable('serialize');
        $.ajax({
            data: data,
            type: 'POST',
            url: 'updatePagesOrder.php'
        });
    }
});

function updateRowIDs()
{
    var i = 1;
    $('table > tbody  > tr').each(function() {
        this.id = 'item-' + i;
        i++;
    });
}



回答3:


Instead of $('tr') inside the .each() loop, use $(this):

$('table > tbody tr').each(function () {
    $(this).attr('id', 'item-' + i);
    i++;
});


来源:https://stackoverflow.com/questions/24577732/re-number-the-ids-of-table-rows-using-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!