小编Nat*_*son的帖子

jQuery在name属性内更改数字

我正在编写一些JavaScript来克隆包含表单元素的表行。

到目前为止,它运行良好,但是其中一件我还不太清楚。

元素名称有一个随行增加的数字。

例如:

<table>
    <tbody>
        <tr>
            <td><input type="text" name="name[0][abc]" /></td>
            <td><button class="add-row-button">+</button></td>
        </tr>
        <tr>
            <td><input type="text" name="name[1][abc]" /></td>
            <td><button class="add-row-button">+</button></td>
        </tr>
    </tbody>
</table>
Run Code Online (Sandbox Code Playgroud)

我需要克隆的行来更新数字。每行中都有多个字段需要此更新的数字,因此我不能仅在jQuery代码中包含新名称。我认为必须发生的是,我需要获取名称,使用正则表达式替换,然后更新属性。

这是我当前的(示例中简化的)jQuery:

// 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++;
});
Run Code Online (Sandbox Code Playgroud)

有人可以指出我正确的方向。在formRowCount++;我需要获取当前元素名称并使用之前更新数字formRowCount

javascript regex jquery

3
推荐指数
1
解决办法
1583
查看次数

标签 统计

javascript ×1

jquery ×1

regex ×1