追加ボタンがクリックされるたびに、テキストボックスと削除ボタンでlistitemを追加する関数を書きました。また、番号を追加して、新しい要素ごとに一意の ID を追加しています。要素を削除してから別の要素を追加しようとすると、問題が発生します。その番号が重複している場合があります。例: 4 つの li を追加し、#3 を削除することにしました。次に、もう一度 [新規追加] をクリックします。新しいシーケンスは、1,2,4,5,6 ではなく 1,2,4,3,4 です。それが理にかなっていることを願っています。
ここに私の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();
});
});
});