Javascript 名称属性中的jQuery更改编号
我正在编写一些JavaScript来克隆包含表单元素的表行 到目前为止,它工作得很好,但有一点我不太清楚 元素名称有一个随每行增加的数字 例如:Javascript 名称属性中的jQuery更改编号,javascript,jquery,regex,Javascript,Jquery,Regex,我正在编写一些JavaScript来克隆包含表单元素的表行 到目前为止,它工作得很好,但有一点我不太清楚 元素名称有一个随每行增加的数字 例如: 有人能给我指一下正确的方向吗。在formRowCount++之前我需要获取当前元素名称,并使用formRowCount更新编号是的,如果需要,可以使用regex var formRowCount = $('table tr').length; $('.add-row-button').click(function() { // Clone
有人能给我指一下正确的方向吗。在
formRowCount++之前
我需要获取当前元素名称,并使用formRowCount
更新编号是的,如果需要,可以使用regex
var formRowCount = $('table tr').length;
$('.add-row-button').click(function() {
// Clone the last row and insert it.
$(this).closest('tr').last().clone().insertAfter($(this).closest('tr'));
// Select the input field
var $newInput = $(this).closest('tr').next().find('input[type="text"]');
// Update the input value and name attribute
var newName = $newInput.attr('name').replace(/^(name\[)\d+(\].+)$/, '$1' + formRowCount + '$2');
$newInput.val('').attr('name', newName);
// Update the number
formRowCount++;
});
对我来说,使用
“name[abc][]”
并调整服务器端代码而不是标题更有意义如果您知道formRowCount
为什么需要知道name[x][abc]
中的值x你所要做的就是使用'name=“name['+formRowCount+'][abc]”
…或者你有什么没有告诉我们的?我也倾向于这样。我本想弄明白这一点,但修改PHP是备份计划,我必须为行中的所有输入元素硬编码它。我发布的代码只是一个基本版本。我正在处理的版本每行有10个表单元素。我想我可以对每个元素都这样做,但我更愿意找到一种使用现有名称attr而不是硬编码的方法。如果更名或将来发生什么事,我就不考虑错误了。我会考虑应该在这个问题上的重要信息。完善…我现在给这个做个测试。
// Current num of elements. Names are 0 based so this will be the number used
// for the new name.
var formRowCount = $('table tr').length;
$('.add-row-button').click(function() {
// Clone the last row.
$(this).closest('tr').last().clone().insertAfter($(this).closest('tr'));
// Set the new field selector.
var $newRow = $(this).closest('tr').next();
$newRow.find('input[type="text"]').val('');
formRowCount++;
});
var formRowCount = $('table tr').length;
$('.add-row-button').click(function() {
// Clone the last row and insert it.
$(this).closest('tr').last().clone().insertAfter($(this).closest('tr'));
// Select the input field
var $newInput = $(this).closest('tr').next().find('input[type="text"]');
// Update the input value and name attribute
var newName = $newInput.attr('name').replace(/^(name\[)\d+(\].+)$/, '$1' + formRowCount + '$2');
$newInput.val('').attr('name', newName);
// Update the number
formRowCount++;
});