方括号之间的Javascript增量数

Lar*_*ars 1 javascript regex jquery increment

这是我的文字输入框

<input class="tb" id="tb43[0]" type="text" size="30" maxlength="200" />
Run Code Online (Sandbox Code Playgroud)

使用jQuery进行克隆时,我希望新克隆框的id为"tb43 [1]".

$clone.find(".tb").attr("id").replace(/\d+/, function (val) { return parseInt(val) + 1; });
Run Code Online (Sandbox Code Playgroud)

这只会增加第一个数字但是如何设法增加方括号中的数字?

谢谢

pim*_*vdb 6

  1. 您可以使用.attr("id", function() {})更改ID.您目前没有更改ID.
  2. 您可以更改正则表达式以仅匹配方括号.
  3. 您可以使用+而不是parseInt(后者有一些警告).

例如

$clone.find(".tb").attr("id", function(i, id) {
  return id.replace(/\[(\d+)\]/, function(match, number) {
    // `number` refers to the first group (denoted with ())
    return "[" + (+number + 1) + "]";
  })
});
Run Code Online (Sandbox Code Playgroud)