每次单击添加按钮时,我都编写了一个函数来添加带有文本框和删除按钮的列表项。我还通过添加一个数字为每个新元素添加一个唯一的 id。当我尝试删除一个元素然后添加另一个元素时会出现问题,有时该数字会重复。例如:我添加了 4 里并决定删除 #3。然后再次单击添加新的新序列是 1,2,4,3,4 而不是 1,2,4,5,6。我希望这是有道理的。
这是我的 javascript
var count = 2;
$('#add').click(function() {
var newTxtBxLi = $('<li></li>').attr('id', 'newli' + count).appendTo('ul');
var input = $('<input type="text" id="newinput' + count + '" name="newinput' + count + '" /><input type="button" id="remove' + count + '" class="remove" value="">');
$(input).appendTo(newTxtBxLi);
count++;
$('.remove').each(function() {
$(this).click(function() {
//count--;
$(this).parent('li').remove();
});
});
});
提前致谢
//更新所以我正在对stackoverflow进行一些研究,并找到了一篇关于执行重复ID检查的帖子。新代码有效,但现在我必须弄清楚如何编写“找到最后一个 id 和 + 1,然后用这个新 id 创建新 li。这是我更新的代码:
$('#add').click(function() {
var count = $('ul > li').length + 1;
var newTxtBxLi = $('<li></li>').attr('id', 'newli' + count).appendTo('ul');
var input = $('<input type="text" id="newinput' + count + '" name="newinput' + count + '" /><input type="button" id="remove' + count + '" class="remove" value="">');
$('ul > li[id]').each(function(){
var ids = $('[id='+this.id+']');
if(ids.length>1 && ids[0]==this){
//console.warn('Multiple IDs #'+this.id);
//find the last id and + 1, then add new listitem
}else{
$(inputAcc).appendTo(newTxtBxLi);
accomplishCount++;
}
});
$('.remove').each(function() {
$(this).click(function() {
count--;
$(this).parent('li').remove();
});
});
});