开发者

jQuery removing an element and renumbering remaining elements

开发者 https://www.devze.com 2023-01-10 11:02 出处:网络
Does anyone see the flaw in my code here, because this one has me stumped! function removeMLRow(rowNo) {

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

function removeMLRow(rowNo) {
    $('#ml_organiz开发者_开发百科e li:eq(' + (rowNo - 1) + ')').remove();
    $($('#ml_organize li:eq(' + (rowNo) + ')').get().reverse()).each(function() {
        var newID = 'li' + ($(this).index() - 1);
        $(this).attr('id',newID);
    });
}


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).


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


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!

0

精彩评论

暂无评论...
验证码 换一张
取 消