这是我在 div 中的表格:
<div class="employmentHistory">
<table class="employmentHistoryForm">
<tr>
<th>Name</th>
<th>Position</th>
<th>Action</th>
</tr>
<tr class = "row">
<td>
<g:textField id="name" name="company" class="company"></g:textField></td>
<td>
<g:textField id="position" name="position" class="pos" ></g:textField></td>
<td><input type="button" class="deleteThisRow" value="Delete"/></td>
</tr>
</table>
<g:textField name="sumCompany" id="destination" ></g:textField>
</div>
这是我克隆上表第二行的 jQuery 脚本:
$(document).ready(function(){
//This line clones the row inside the '.row' class and transforms it to plain html.
//var clonedRow = $('.row').clone().html();
var clonedRow=$('.row').clone().html().find("input").each(function() {
$(this).val('').attr('id', function(_, id) { return id + index });
}).end();
//This line wraps the clonedRow and wraps it <tr> tags since cloning ignores those tags
var appendRow = '<tr class = "row">' + clonedRow + '</tr>';
$('#btnAddMore').click(function(){
//this line get's the last row and appends the appendRow when it finds the correct row.
$('.employmentHistoryForm tr:nth-child(2)').after(appendRow);
});
//when you click on the button called "delete", the function inside will be triggered.
$('.deleteThisRow').live('click',function(){
var rowLength = $('.row').length;
//this line makes sure that we don't ever run out of rows.
if(rowLength > 1){
deleteRow(this);
}else{
$('.employmentHistoryForm tr:last').after(appendRow);
deleteRow(this);
}
});
function deleteRow(currentNode){
$(currentNode).parent().parent().remove();
}
index++;
});
将上述脚本中的行用作:
var clonedRow = $('.row').clone().html();
该代码完美地克隆了表行并将其附加到表的末尾。但它复制了文本字段的 id 字段,我想为克隆的行分配唯一的 id,我尝试如下:
var clonedRow=$('.row').clone().html().find("input").each(function() {
$(this).val('').attr('id', function(_, id) { return id + index });
}).end();
但是现在查询根本不起作用。那么我在哪里弄错了,解决方案是什么?