找到1并用正则表达式替换它

时间:2014-02-20 15:22:07

标签: jquery regex

我正在尝试复制表单,并根据表单的数量将值1替换为2,3等。

这是我的html:

<div id="clonedInput1" class="clonedInput">

  <input id="show_upload_image_link_1" type="text" size="36" name="kandibox_theme_hero_options[show_upload_image_link_1]" value="<?php echo $hero_options['show_upload_image_link_1']; ?>" /> 
 <input id="show_upload_image_link_button_1" class="button upload_images" type="button" value="Upload Image" />

  <div class="actions">
      <button class="clone">Clone</button> 
      <button class="remove">Remove</button>
  </div>
</div>

这是我的疑问:

var regex = /^([0-9]+)$/;
var cloneIndex = $(".clonedInput").length;

$("button.clone").live("click", function(){
  $(this).parents(".clonedInput").clone()
    .appendTo("body")
    .attr("id", "clonedInput" +  cloneIndex)
    .find("*").each(function() {
        var id = this.id || "";
        var match = id.match(regex) || [];
        if (match.length == 3) {
            this.id = match[1] + (cloneIndex);
  }
});
cloneIndex++;
});

$("button.remove").live("click", function(){
  $(this).parents(".clonedInput").remove();
});

到目前为止,它添加了额外的表单,但它不会替换名称或值中的值1。

这是一个小提琴http://jsfiddle.net/tfFLt/590/

1 个答案:

答案 0 :(得分:2)

最终版本需要清理以避免代码重复:

$("button.clone").live("click", function(){
    var cloneIndex = $(".clonedInput").length + 1;
    var new_Input = $(this).parents(".clonedInput").clone();
    updateClonedInput(cloneIndex, new_Input);    
});

$("button.remove").live("click", function(){
    $(this).parents(".clonedInput").remove();

    $(".clonedInput").each( function (cloneIndex, clonedElement) {
        updateClonedInput(cloneIndex + 1, clonedElement);
    })
});

对于input ID计算和其他属性,我完全删除了正则表达式。我还改变了处理新输入的方式:首先我创建一个newInput,然后我处理它。更简单,更易读的方法。

当您删除一个输入时,input字段也将重新编号为1,2,3 ... 小提琴已经更新以反映这一点。

PS。注意,如果你删除了第一个输入,那么你就没有更多的输入区域或按钮来添加新的... :-)解决方案:要么从输入表单中删除此按钮,要么将条件设置为不允许如果只剩下一个输入,则删除。

希望它有所帮助!

Fiddle