使用 Jquery 和增量表单字段名称的表单克隆

Form Cloning using Jquery with increment form fields name

我的表单有两个字段,分别是简短描述和详细描述,最初表单字段的名称是 section[new][1][description]section[新][1][l描述]

我想生成克隆表单字段,这些字段会生成像 section[new][2][description]section[new][2] 这样的名称[描述]。 每次我克隆新表单时,它都应该生成表单字段名称,中间带有增量 ID,例如 section[new][incrementid goes here][description]

如何使用正则表达式或任何其他 jquery 技术实现此目的?

这是我用于表单克隆的代码

jQuery("button.add").on("click", clone); 

function clone(){
var clone = jQuery(this).parents(".pbone_section_default").clone()
    .appendTo("#section_list")
    .attr("id", "pbone_section_default_" +  cloneIndex)
    .find("*")
    .each(function() {
        // here we can put any logic to achieve desire element name  
        this.name = logic goes here;
    })
    .on('click','button.delete',remove);
};

是的,它可以完成(你很接近)。假设你正在使用基于 0 的索引(即从 section[new][0][description] 开始),试试这个代码:

function clone(){
    var $clone = $(".pbone_section_default").last(),
        index = $clone.index();

    $clone.clone()
          .appendTo("#section_list")
          .find("[name*='["+index+"]']")
          .each(function(){
            $(this).attr("name", $(this).attr("name").replace("["+ index +"]", "["+ parseInt(index+1) +"]"));
          });
};

在此处查看工作示例:FIDDLE

无论如何,我建议你改用模板引擎,比如Mustache or Underscore.. but there are plenty of them.. check this article,看看哪个更适合你的项目

您可以使用 .match().replace() 来查找字符串中的数字并递增它:

.each(function() {
    this.name = incrementNumberinString(this.name);
});

var incrementNumberinString = function (string){
  var i = parseInt(string.match(/\d{1}/g))+1;
  return string.replace(/\d{1}/g, i)
}

正则表达式将找到正好存在 1 次的任何数字。

有关正则表达式的示例,请参阅 here

注意:这仅在假设您的输入名称中只有 1 个数字的情况下有效。

Working Example