我写了一个函数来添加带有文本框和删除按钮的listitem,每次添加按钮被点击。我还通过添加一个数字为每个新元素添加一个唯一的ID。问题发生在我尝试删除元素时,然后添加另一个元素,有时该数字被重复。例如:我添加4个李,并决定删除#3。然后点击再次添加新的序列是1,2,4,3,4而不是1,2,4,5,6。我希望这是有道理的。
这里是我的javascript使用jQuery来添加和删除带有唯一ID的文本框
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();
});
});
});
感谢,提前
//更新 ,所以我在做计算器上的一些研究,发现一个帖子有关执行重复的ID的检查。新代码的工作,但现在我必须弄清楚如何写“找到最后一个ID和+ 1,然后用这个新的ID创建新丽 这里是我更新的代码:
$('#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();
});
});
});
谢谢帕特里克!棒极了! – Gerald 2010-10-07 19:00:02
@Gerald - 这是否发生了解决重复ID问题?它似乎没有完全相关,但不确定它是否可能导致一些意想不到的行为。 – user113716 2010-10-07 19:13:26
不,我仍然试图弄清楚这一点 – Gerald 2010-10-07 19:14:12