【发布时间】:2013-08-02 16:54:54
【问题描述】:
这是我在 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();
但是现在查询根本不起作用。那么我在哪里弄错了,解决方案是什么?
【问题讨论】:
-
如果您想克隆具有唯一 ID 的元素,那么这些元素确实不是唯一的,因此不应具有唯一 ID。为什么不给他们上课呢?
-
@BradM 好的,即使提供类也可以,但文本字段的每一行中的类必须是唯一的。我应该如何通过对上述代码的最小更改来实现这一点?
-
我不知道你背后的逻辑/推理,但我认为你过度分析了这一点。唯一需要唯一的是行(如果您基于索引,从技术上讲已经是唯一的),但是您可以为行提供 data-* 属性以获得更精确的唯一性。无论在一行中单击什么文本框/按钮,始终向上遍历 dom 到唯一行并读取它的索引/数据-*。一旦您知道事件发生的唯一行,您就可以以此为基础制定逻辑。