jQuery removing an element and renumbering remaining elements

前提是你 提交于 2020-01-04 09:16:29

问题


Does anyone see the flaw in my code here, because this one has me stumped!

function removeMLRow(rowNo) {
    $('#ml_organize li:eq(' + (rowNo - 1) + ')').remove();
    $($('#ml_organize li:eq(' + (rowNo) + ')').get().reverse()).each(function() {
        var newID = 'li' + ($(this).index() - 1);
        $(this).attr('id',newID);
    });
}

回答1:


I can't say for sure based on the question, but I think this is what you're after:

function removeMLRow(rowNo) {
    $('#ml_organize li').eq(rowNo - 1).remove();
    $('#ml_organize li').slice(rowNo -1).each(function() {
        var newID = 'li' + ($(this).index() + 1);
        $(this).attr('id',newID);
    });
}

First, you can use .eq() instead of :eq() to just make things cleaner. Then we're using .slice() to get all the <li> elements after the one we removed and are numbering only those <li>'s. You could use :gt() (greater-than-index), but .slice() just trims down on the string concatenation (and is a bit faster, infinitesimal difference though).




回答2:


Are you sure you should be using reverse. from what i see you're removing an element and then renumbering back to the top. should you be renumbering to the bottom or are the numbers reversed?

more info please @dave




回答3:


Nick, you were ALMOST there! Needed to (+1) instead of (-1) in the newID.

function removeMLRow(rowNo) {
    $('#ml_organize li').eq(rowNo - 1).remove();
    $('#ml_organize li').slice(rowNo - 1).each(function() {
        var newID = 'li' + ($(this).index() + 1);
        $(this).attr('id',newID);
    });
    var item_positions = $('#ml_organize').sortable('toArray');
    alert(item_positions);
}

Thanks to all for your help!



来源:https://stackoverflow.com/questions/3392461/jquery-removing-an-element-and-renumbering-remaining-elements

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