我有一个小脚本,用于复制表的行并将新行附加到表的末尾。但是每个单元格包含一个元素,其名称类似于“ Details [0] .Amount”。克隆一行时,我只想通过增加旧索引的索引部分(如“ Details [1] .Amount”)来设置其名称。这是我的代码:
var clonedRow = $('#body tr:first').clone();
clonedRow.find('input').val(''); //set its name
$('#body').append(clonedRow);
答案 0 :(得分:1)
只需直接或通过jQuery的prop()
方法设置输入的urca
属性即可。
name
要进行实际替换,根据名称的结构,您可以简单地使用正则表达式替换(\ d匹配数字)
var index = 1; //do whatever you need to determine the correct index
//uses template literal to build the name
clonedRow.find('input').prop('name',`Details[${index}].Amount`);
如果名称更复杂,显然需要使用更复杂的代码。
演示
newName = oldName.replace(/\d/,index);
jQuery('button').click(()=>{
var clone = $('table tr:first').clone();
var index = $('table tr').length;
var input = clone.find('input');
var oldName = input.prop('name');
//replace the first number occurance with index
var newName = oldName.replace(/\d/,index);
input.prop('name',newName).val(newName);
$('table').append(clone);
});
答案 1 :(得分:0)
在String#replace()
或prop(propname,function)
内使用attr(attrName,function)
$('button').click(function() {
var clone = $('table tr:first').clone();
var index = $('table tr').length;
clone.find('input').prop('name', function(_, curr) {
return curr.replace(/\d+/, index);
})
// set value as name just for demo
.val(function() {
return this.name
});
$('table').append(clone);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
<td><input name="Details[0].Amount" /></td>
<td><input name="Details[0].Foo" /></td>
</tr>
</table>
<button>Clone</button>
答案 2 :(得分:0)
我不是js专家,但我猜一个可能的解决方案是使用正则表达式,并且使用类似
var val ="Details[0].Amount";
val=val.replace(/\d+/,function(elm){return (parseInt(elm))+1});