對於這個神祕的標題很抱歉,很難形容!刪除任何元素,重新分配計數值
我使用下面的腳本添加一行到我的形式單擊按鈕時:
$(document).ready(function() {
$('#btnAdd').click(function() {
var num = $('.clonedInput').length;
var newNum = new Number(num + 1);
var newElem = $('#input' + num).clone().attr('id', 'input' + newNum);
newElem.children(':first').attr('id', 'name' + newNum).attr('name', 'name' + newNum);
$('#input' + num).after(newElem);
$('#btnDel').attr('disabled','');
if (newNum == 5)
$('#btnAdd').attr('disabled','disabled');
});
$('#btnDel').click(function() {
var num = $('.clonedInput').length;
$('#input' + num).remove();
$('#btnAdd').attr('disabled','');
if (num-1 == 1)
$('#btnDel').attr('disabled','disabled');
});
$('#btnDel').attr('disabled','disabled');
});
這工作絕對沒問題,但它不是很人性化的,你只能刪除最後添加行。假設我想刪除之前添加的一行,我將不得不刪除我從那時起所做的一切。
如何刪除任何行,並同時將計數值重新分配給其他行,以便計數仍然是順序的(即Row1,Row2,Row3等,而不是Row1,Row5,Row8)?
我不知道如何告訴它刪除的內容元素,而無需顯式的ID。 我現在有: var num = $('。clonedInput')。prevAll()。size(); \t $('#input')。remove(); 沒有輸入num,它怎麼知道要刪除什麼? – Tom 2009-11-19 17:07:51
我已經發布了一個例子。無論如何,您都可以使用$(this)和jQuery選擇器來操縱DOM。每個元素的特定ID不是必需的。 – kgiannakakis 2009-11-19 19:16:41