在删除一些数据后如何使附加元素重新排序?我做了一个例子,删除后附加的数字保持不变。
$(document).ready(function(){
$('.do-append').on('click', function(){
var index = $('append div').length;
$('append').append('<div><label>Appended : '+index+'</label>   <a href="javascript:;" class="delete" style="color: red">delete</a></div>');
});
$('append').on('click', '.delete', function(e){
$(e.target).closest('append div').remove();
});
})
<html lang="en">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<a href="javascript:;" class="do-append">click me</a><br><br>
<append></append>
</body>
</html>
答案 0 :(得分:1)
您可以尝试使用以下逻辑,在该逻辑中可以更新div下已删除元素之后的标签。
$(document).ready(function(){
$('.do-append').on('click', function(){
var index = $('append div').length;
$('append').append('<div><label>Appended : '+index+'</label>   <a href="javascript:;" class="delete" style="color: red">delete</a></div>');
});
$('append').on('click', '.delete', function(e){
var $parent = $(e.target).closest('append div');
var index = $parent.index();
$parent.remove();
if(index>0) {
$('append div:gt('+ (index-1) +')').each(function(){
$('label', this).html('Appended : '+index);
index++;
});
} else {
$('append div').each(function(){
$('label', this).html('Appended : '+ index);
index++;
});
}
});
})
<html lang="en">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<a href="javascript:;" class="do-append">click me</a><br><br>
<append></append>
</body>
</html>
答案 1 :(得分:0)
创建如下所示的updateLabels
函数,并在添加和删除项目时调用
function updateLabels() {
var index = $('append div').length;
for (var i = 0; i < index; i++) {
$($($('append div')[i]).find("label")[0]).text('Appended : ' + i);
}
}
$(document).ready(function() {
$('.do-append').on('click', function() {
var index = $('append div').length;
$('append').append('<div><label></label>   <a href="javascript:;" class="delete" style="color: red">delete</a></div>');
updateLabels();
});
$('append').on('click', '.delete', function(e) {
$(e.target).closest('append div').remove();
updateLabels();
});
function updateLabels() {
var index = $('append div').length;
for (var i = 0; i < index; i++) {
$($($('append div')[i]).find("label")[0]).text('Appended : ' + i);
}
}
})
<html lang="en">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<a href="javascript:;" class="do-append">click me</a><br><br>
<append></append>
</body>
</html>