javascript 如何使用 jquery 克隆或复制字段?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9441289/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 06:41:42  来源:igfitidea点击:

how to clone or duplicate fields with jquery?

javascriptjqueryhtml

提问by ReynierPM

I have this markup

我有这个标记

<div class="input text">
   <label for="Experience0ExperienceContent">Experience Content</label>
   <input name="data[Experience][0][experience_content]" class="span3" id="Experience0ExperienceContent" type="text">
</div>

It's possible to clone or duplicate it incrementing the 0 value every time the user make click on a link? I mean all the 0 when user clicks one time the link need to go to 1 then if click again need to go to 2 and so on and of course maintaining the same markup every time, any advice or help?

每次用户单击链接时,是否可以克隆或复制它并增加 0 值?我的意思是当用户点击一次链接需要转到 1 时所有的 0 然后如果再次点击需要转到 2 等等,当然每次都保持相同的标记,有什么建议或帮助吗?

Cheers and thanks in advance

提前干杯和感谢

回答by nnnnnn

You could try a little something like this:?

你可以试试这样的东西:?

$("a").click(function() {        
    $("div.input.text")
        .last()
        .clone()
        .appendTo($("body"))
        .find("input").attr("name",function(i,oldVal) {
            return oldVal.replace(/\[(\d+)\]/,function(_,m){
                return "[" + (+m + 1) + "]";
            });
        });        
    return false;        
});

As demonstrated here: http://jsfiddle.net/6Xg4S/

如此处所示:http: //jsfiddle.net/6Xg4S/

Essentially on click of your anchor it will clone the last div and append it to the body (at least my example appends to the body - obviously you could append it to something more specific or .insertAfter()the last one), then take the number from the middle of the name and increment it via a regex replace.

基本上点击你的锚点它会克隆最后一个 div 并将其附加到正文(至少我的示例附加到正文 - 显然你可以将它附加到更具体的内容或.insertAfter()最后一个),然后从中间取数字名称并通过正则表达式替换增加它。

Having done that though I'd like to note that you don't need to give your inputs unique names: all of the server-side technologies that I'd care to use can deal with multiple request parameters with the same name (e.g., Java has getParameterValues()that returns an array).

完成此操作后,我想指出您不需要为输入提供唯一名称:我想使用的所有服务器端技术都可以处理具有相同名称的多个请求参数(例如, Java 有getParameterValues()返回一个数组)。

EDIT:Here's a version that clones only the input element, specifically the last input in the div, updates its id, and appends it to the end of the div. As per your comment this no longer changes the name (though obviously you can just throw in an additional .attr()call as above if you want to change the name too). Oh, and also this sets the value to blank (I forgot to do that above).

编辑:这是一个仅克隆输入元素的版本,特别是 div 中的最后一个输入,更新其 id,并将其附加到 div 的末尾。根据您的评论,这不再更改名称(尽管很明显.attr(),如果您也想更改名称,则可以像上面那样进行额外的调用)。哦,这也将值设置为空白(我忘了在上面这样做)。

$("#extra a").click(function() {   
    var $div = $(this).next();
    $div.find("input")
        .last()
        .clone()
        .appendTo($div.append("<br/>"))
        .val("")
        .attr("id",function(i,oldVal) {
            return oldVal.replace(/\d+/,function(m){
                return (+m + 1);
            });
        });
    return false;
});

Demo: http://jsfiddle.net/6Xg4S/4/

演示:http: //jsfiddle.net/6Xg4S/4/

回答by JulioC

First of all, give it an id for better selector performance, I'll assume it foofor the link, barfor the field:

首先,给它一个 id 以获得更好的选择器性能,我假设它foo用于链接,bar用于字段:

function buildId(id) {
  return 'data[Experience][' + id + '][experience_content]';
}

jQuery('#foo').click((function () {
  var i = 0;
  return function () {
    var $bar = jQuery('#bar');
    $bar
      .clone()
      .attr('id', buildId(i++))
      .insertAfter($bar);
  };
})());

Check the jQuery APIfor the methods used.

检查jQuery API以了解使用的方法。

回答by DG3

You can use jquery clone() method and then retrieve the actual element's name, and then update the new elements name. Read herefor more

您可以使用 jquery clone() 方法,然后检索实际元素的名称,然后更新新元素名称。在这里阅读更多

Heres an example

这是一个例子

  <!DOCTYPE html> 
<html> 

<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1"> 
    <title>Single page template</title> 
    <script src="http://code.jquery.com/jquery-1.6.4.min.js"></script>
</head> 


<body> 
<a href="#" id="cloneme" name="cloneme">Clone Me</a>
<div class="input text">
   <label for="Experience0ExperienceContent">Experience Content</label>
   <input name="data[Experience][0][experience_content]" class="span3" id="Experience0ExperienceContent" type="text">
    <input type="hidden" id="currentval" name="currentval" value="0" />

</div>

<script type="text/javascript">
    $(document).ready(function(){
        $("a").click(function(){
            var currentval = parseInt($("#currentval").val()) + 1;
            var cloneme = $("#Experience0ExperienceContent").clone();
            var newid = "Experience" + currentval + "ExperienceContent";
            cloneme.attr("id",newid);
           $("#currentval").val(currentval);
            $("div").append(cloneme);
        });
    })
</script>


</body>
</html>

Edit:

编辑:

Here is the link to code in jsfiddle: http://jsfiddle.net/kYwXX/1/

这是 jsfiddle 中代码的链接:http: //jsfiddle.net/kYwXX/1/