我寫了一個函數來添加帶有文本框和刪除按鈕的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