0

我正在尝试通过 jQuery 动态添加行,但不是添加 1 行,而是一次添加 2 行。

这是代码:

jQuery代码:

$(document).ready(function() {
  var current_id = 1;
  $('#add').click(function(){
  next_element($('#timesheetrow1'));
 })

 function next_element(element){
 var new_element = element.clone(),
    id = current_id + 1;
    current_id = id;

if (id <7) {
    new_element.attr("id",element.attr("id").split("1")[0]+id);

    $(':input', new_element).each(function(){
      var field_id = $(this).attr("id"),
          field_name = $(this).attr("name");
      $(this).attr("id", field_id.split("1")[0]+id );
      $(this).attr("name", field_name.split("1")[0]+id );
    });
    new_element.appendTo($("#timesheet-rows"));
  }
   };
 });

和 HTML 代码:

<div id="timesheet-rows">
    <div id="timesheetrow1" class="timesheet-row">

    <input type="text" id="FinalNumber1" name="FinalPONumber1" width="50" />                                         
    <input type="text" id="FinalAmount1" name="FinalPOAmount1" width="50" />                                           
   </div>

   </div>
  <input type="button" value="Add" class="add" id="add" class="GreenBTN"/>
4

1 回答 1

0

The jQuery clone method makes a deep copy of the element specified. By cloning and appending, you'll get exponential growth instead of linear. I.e., when you add one the first time, you're ok, but the second time, you'll copy the original element and the child you added, so you'll add 2 instead of 1. Next time, you'll copy the original and its 3 children, and add 4 instead of 1, and so on.

One way to avoid this issue is to use javaScript's cloneNode instead of jQuery clone. This gives you the option to make it a deep or shallow clone:

next_element(document.getElementById("timesheetrow1"));

var new_element = element.cloneNode(false);
于 2013-10-01T16:52:34.657 回答