简体   繁体   English

如何使用jQuery克隆和追加多个元素?

[英]How do I clone and append multiple elements in place with jQuery?

What is a simple way to duplicate every element in a class as a sibling? 什么是将类中的每个元素复制为兄弟的简单方法? For example, it should change this HTML: 例如,它应该更改此HTML:

<body>
    <div> 
        <h1> Foos </h1>
        <span class='duplicate-me'> foo </span>
    </div>
    <div>
        <h1> Bars </h1> 
        <span class='duplicate-me'> bar </span>
    </div>
</body>

into: 成:

<body>
    <div> 
        <h1> Foos </h1>
        <span class='duplicate-me'> foo </span>
        <span class='duplicate-me'> foo </span>
    </div>
    <div>
        <h1> Bars </h1> 
        <span class='duplicate-me'> bar </span>
        <span class='duplicate-me'> bar </span>
    </div>
</body>

Thanks 谢谢

There you go - append to the parent element after cloning the duplicate-me element. 你去 - cloning duplicate-me元素后append到父元素。

See demo below: 见下面的演示:

 $(function(){ $('.duplicate-me').each(function(){ $(this).parent().append($(this).clone()); }); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <body> <div> <h1> Foos </h1> <span class='duplicate-me'> foo </span> </div> <div> <h1> Bars </h1> <span class='duplicate-me'> bar </span> </div> </body> 

$('.duplicate-me').after(function() {
  return $(this).clone();
});

Use the after method from jQuery and call the clone method in the function you are passing to it. 使用jQuery中的after方法,并在要传递给它的函数中调用clone方法。

References: http://api.jquery.com/after/ 参考文献: http //api.jquery.com/after/

http://api.jquery.com/clone/ http://api.jquery.com/clone/

Example: https://jsfiddle.net/2y6cqLrq/ 示例: https //jsfiddle.net/2y6cqLrq/

Use insertAfter to insert the duplicate element created using clone just next to it 使用insertAfter插入使用克隆旁边创建的重复元素

 $(function(){ $('.duplicate-me').each(function(){ $(this).clone().insertAfter($(this)) }) }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <body> <div> <h1> Foos </h1> <span class='duplicate-me'> foo </span> </div> <div> <h1> Bars </h1> <span class='duplicate-me'> bar </span> </div> </body> 

All you need is: 所有你需要的是:

1)Clone elements with .duplicate-me class. 1)使用.duplicate-me类克隆元素。

2)Append those elements to closest div, which is their parent . 2)将这些元素附加到closest div,即它们的parent

Please try this: 请试试这个:

$('.duplicate-me').each(function(){
    var clone= $(this).clone();
    $(this).closest('div').append(clone);
});

References: 参考文献:

 $('.duplicate-me').each(function(){ var clone= $(this).clone(); $(this).closest('div').append(clone); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <body> <div> <h1> Foos </h1> <span class='duplicate-me'> foo </span> </div> <div> <h1> Bars </h1> <span class='duplicate-me'> bar </span> </div> </body> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM