具有独立值的克隆行
问题描述:
我遇到了一些问题。我有以下两张表具有独立值的克隆行
<table id="customFields1" class="table table-bordered table-hover additionalMargin alignment">
<thead>
<tr>
<th colspan="2"></th>
<th>Some Title</th>
</tr>
</thead>
<tbody>
<tr>
<td><label class="subjectline" for="User1">User NOC M1</label></td>
<td id="slLabel">SL_A</td>
<td id="slInput"><input type="text" name="slOptions[User][NOC M1]" class="form-control" id="User1"></td>
<td><a class="addCF" href="javascript:void(0);">+ additional user</a></td>
</tr>
</tbody>
</table>
<table id="customFields2" class="table table-bordered table-hover additionalMargin alignment">
<thead>
<tr>
<th colspan="2"></th>
<th>Some Title</th>
</tr>
</thead>
<tbody>
<tr>
<td><label class="subjectline" for="User1">User NOC M1</label></td>
<td id="slLabel">SL_A</td>
<td id="slInput"><input type="text" name="slOptions[User][NOC M1]" class="form-control" id="User1"></td>
<td><a class="addCF" href="javascript:void(0);">+ additional user</a></td>
</tr>
</tbody>
</table>
两者都有一个addCF按钮。这用于向表中添加一个新行。这是通过这个实现的
$(function() {
alp = "A";
regexp = /[_A]+$/;
$(".addCF").click(function(){
alp = (alp.substring(0,alp.length-1)+String.fromCharCode(alp.charCodeAt(alp.length-1)+1));
var clone = $(this).closest('tr').clone(true);
var inputOrgLabel = $("td:nth-child(2)", clone).html();
inputOrgLabel = inputOrgLabel.replace(regexp,'');
$("td:nth-child(2)", clone).html(inputOrgLabel+'_'+alp);
$("td:first-child", clone).empty();
$("td:last-child", clone).html('<a href="javascript:void(0);" class="remCF">Remove</a>');
clone.insertAfter($(this).closest('table').find('tr:last'));
});
$("table.table").on('click','.remCF',function(){
$(this).parent().parent().remove();
});
});
除了一件事情之外,一切似乎都奏效。如果我添加一个新行,我将标签SL_A更改为SL_B。添加的每一行都在其末尾添加了字母表中的下一个字母。这是行得通的,但如果我在表1中添加一行,使其成为SL_B,然后在表2中添加一行,则表2中的行具有SL_C。每个字母增量应该是独立的,所以表2中的第二行也应该有SL_B。
这可能吗?我已成立了一个JSFiddle证明
感谢
答
我已经在高山牵着你的数据的阵列和相应的改变。在这里,我可以得到单击按钮的索引,以使用该索引作为apl数组的索引。
$(function() {
alp = [];
$.each($('.addCF'), function(i,v) {
alp[i] = "A";
})
regexp = /[_A]+$/;
$(".addCF").click(function(e){
index = $('.addCF').index($(this));
alp[index] = (alp[index].substring(0,alp[index].length-1)+String.fromCharCode(alp[index].charCodeAt(alp[index].length-1)+1));
var clone = $(this).closest('tr').clone(true);
var inputOrgLabel = $("td:nth-child(2)", clone).html();
inputOrgLabel = inputOrgLabel.replace(regexp,'');
$("td:nth-child(2)", clone).html(inputOrgLabel+'_'+alp[index]);
$("td:first-child", clone).empty();
$("td:last-child", clone).html('<a href="javascript:void(0);" class="remCF">Remove</a>');
clone.insertAfter($(this).closest('table').find('tr:last'));
});
$("table.table").on('click','.remCF',function(){
$(this).parent().parent().remove();
});
});
注意:您必须管理删除代码,因为它不会重置该值。
谢谢你的解决方案。但我看到有一个问题。我不知道会有多少表,因为它们会根据其他一些数据动态添加。这个解决方案完美地适应两张桌子,但只有两张。有没有办法处理X数量的表格?谢谢 –
好吧。给我一分钟。我会更新答案 –
我已经更新了答案。现在它会按照你的要求工作:) –