如何使用javascript或jquery创建tr的克隆并在新行中插入数据?

时间:2013-09-20 13:44:19

标签: javascript jquery

<tr id="rptShippinRates_ctl01_A" class="row">
  <td>
    <div>
      <input type="hidden" id="hdnSupplierShippingID" value="28">
    </div>
    <div class="gvColSet tLightBlack gvColAlignLeft" style="font-size: 12px;" title="Test1">Test1</div>
  </td>
  <td>
    <div class="gvColSet tLightBlack gvColAlignLeft" style="font-size: 12px;" title="$ 10.00">$ 10.00</div>
  </td>
  <td>
    <span id="SpnDeleteShipping" class="DelRow" title="Delete shipping rate" style="float: Left;margin-left: 8px;"></span>
  </td>
</tr>

我想使用JavaScript或jQuery来克隆它。任何帮助将不胜感激。

2 个答案:

答案 0 :(得分:0)

类似的东西:

HTML:

<table>
<tr id="rptShippinRates_ctl01_A" class="row">
<td>
       <div>
        <input type="hidden" id="hdnSupplierShippingID" value="28">
       </div>
       <div class="gvColSet tLightBlack gvColAlignLeft" style="font-size: 12px;" title="Test1">Test1</div>
  </td>
<td>
     <div class="gvColSet tLightBlack gvColAlignLeft" style="font-size: 12px;" title="$ 10.00">$ 10.00
     </div>
     </td>
<td>
   <span id="SpnDeleteShipping" class="DelRow" title="Delete shipping rate" style="float: Left;margin-left: 8px;"></span>
   </td>
    </tr>
    </table>

JS:

$('tr').clone().appendTo('table');

JSfiddle:http://jsfiddle.net/P8Tkf/ 你也必须删除id,因为id必须是唯一的。

答案 1 :(得分:0)

var $tr = $('tr.row'); // fidn the row you want to work with

$tr // grab the row
  .clone() // clone it
  .prop('id','...') // change its id
  .find('td:eq(0)') // find the first <td>
    .find('input') // find hidden input
      .val('...') // change its value
    .end()
    .find('.gvColSet') // find the nested gvColSet
      .text('...') // change its text
      .prop('title','...') // and change its title
    .end()
  .end()
  .find('td:eq(1)') // find second <td>
    .find('.gvColSet') // find the nested gvColSet
      .text('...') // change its text
      .prop('title','...') // and its title
    .end()
  .end()
  .appendTo($tr.closest('table')); // append it to the same table