简体   繁体   English

克隆每个元素追加下一个元素

[英]Clone each element append next element

I need to .Clone each a to inside the next elment which is ul我需要将每个 a 克隆到下一个 ul 元素内

How can i do that ?我怎样才能做到这一点 ?

<ul>

<li>
<a>link<a>
<ul></ul>
<li>

<li>
<a>link<a>
<ul></ul>
<li>

<li>
<a>link<a>
<ul></ul>
<li>

<li>
<a>link<a>
<ul></ul>
<li>

</ul>

I have tried:我试过了:

$("a").each(function () {
    $(this).clone().insertAfter(this).find('ul');
});

The problem is i get the new cloned elment just beside the original one, i wish to insert it inside the next ul elment问题是我在原来的旁边得到了新的克隆 elment,我希望将它插入下一个 ul elment

thanks谢谢

You need to find the next list, then append the clone d element.您需要找到next列表,然后append clone d 元素。 I also fixed your invalid HTML:我还修复了您的无效 HTML:

 $("a").each(function() { $(this).next("ul").append($(this).clone(true)); });
 <script src="https://code.jquery.com/jquery-3.3.1.js"></script> <ul> <li><a>link</a> <ul></ul> </li> <li><a>link</a> <ul></ul> </li> <li><a>link</a> <ul></ul> </li> <li><a>link</a> <ul></ul> </li> </ul>

Valid HTML requires that <ul> can only have <li> as a direct descendant (child).有效的 HTML 要求<ul>只能将<li>作为直接后代(子项)。 A <li> can have anything within itself, but it needs to end properly with a </li> . <li>本身可以包含任何内容,但它需要以</li>结尾。 The demo follows the following pattern:该演示遵循以下模式:

 <ul><!------------------------------Main List--> <li><!----------------------------List Item--> <a href='#/'>LINK 1</a><!---Original Link--> <ul><!------------------------Target List--> <li><!--------------------New List Item--> <a href='#/'>LINK 1</a><!--Clone Link--> </li> </ul> </li> ... </ul>

Demo演示

 /* .each() <a> Create a .clone() of current <a> Find .next() <ul> .append() the clone to <ul> .wrapInner() of <ul> with a <li> */ $("a").each(function() { var dupe = $(this).clone(true, true); $(this).next('ul').append(dupe).wrapInner(`<li></li>`); });
 <ul> <li> <a href='#/'>LINK 1</a> <ul></ul> </li> <li> <a href='#/'>LINK 2</a> <ul></ul> </li> <li> <a href='#/'>LINK 3</a> <ul></ul> </li> <li> <a href='#/'>LINK 4</a> <ul></ul> </li> </ul> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

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

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