问题
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