删除任何元素,重新分配计数值

对于神秘的标题感到抱歉,很难描述!

单击按钮时,我使用以下脚本向表单添加行:

$(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。 相反,您可以使用jQuery强大的选择器来获取元素的位置。

这是一个基于常见html结构的示例。 发布您自己的HTML以获取更多详细信息。

  $('.btnDel').click(function() { var num = $(this).parent().prevAll().size(); // this points to delete link. // The previous element is the content element $(this).prev().remove(); $('#btnAdd').attr('disabled',''); if (num-1 == 1) $(this).attr('disabled','disabled'); }); 
.... Delete

你为什么甚至在行中添加ID? 请记住,83%的jQuery是“查询” – 使用选择器来获取所需的元素。

我不得不做了类似的事情

基本上我得到了删除行的编号,即。 Row3然后循环通过更新其值的其余行。 所以Row4成为Row3等

我用过这样的东西

  var last_val = //get the last value of the rows so you know when to stop //knock off the Row part of the id and parses as an integer var pos = parseFloat(row_id.slice(3)) var next_val = position+1; var prev_val = position; while(next_val<=last_val){ next_selector = "#Row"+next_val; prev_id = "Row"+prev_val; $(next_selector).attr("id",prev_id); next_val++; prev_val++; } 

可能有更好的方法可以做到这一点,但这对我来说是一个cms,允许从列表中间删除页面,然后更新行编号。

我在这里发布了一个演示 (由于浮动,它在IE中看起来不太好,但我只想发布这个例子来帮助)。 我不知道你如何处理收集表单数据,所以我确实包括重新编号克隆的输入ID。

CSS

 form { width: 400px; margin: 0 auto; line-height: 30px; } input { float: right; } 

HTML

 
Name:
Title:
Company:
Location:
Additional information:

脚本

 $(document).ready(function(){ $('#btnAdd').click(function(){ // inputs reversed because of the float right var newInput = '
Additional Field : ' + '
'; $(newInput).appendTo('#addFields'); // disable add button if there are 5 additional fields if ($('.clonedInput').length == 5) { $('#btnAdd').attr('disabled','disabled'); } renumber(); }) // Delete input field $('.btnDel').live('click',function(){ $('#btnAdd').attr('disabled',''); $(this).parent().remove(); renumber(); }) }) // This function adds the additional field number and ID for each clonedInput field function renumber(){ $('.clonedInput').each(function(i){ $(this).find('span').html('#' + (i+1)); // the code below will change the ID of the input, in case you collect your data based on the ID. $(this).find('input[type=text]').attr('id', 'input' + (i+1)); }) }