合并和插入来自两个父元素的元素

我有两个部分,里面有动态数量的元素。我想将这两个部分合并并插入它们的项目。


最初它会是这样的:


<section class="first">

 <div>One</div>

 <div>Two</div>

 <div>Three</div>

</section>


<section class="second">

 <div>Four</div>

 <div>Five</div>

 <div>Six</div>

</section>

以及所需的输出:


<section class="merged">

 <div>One</div>

 <div>Four</div>

 <div>Two</div>

 <div>Five</div>

 <div>Three</div>

 <div>Six</div>

</section>

到目前为止,这是我的尝试,但我无法显示结果:


var array1 = $( ".first div" ).toArray()

var array2 = $( ".second div" ).toArray()


var arrayCombined = $.map(array1, function(v, i) { return [v, array2[i]]; });

有人知道我怎样才能实现这一目标吗?谢谢


慕桂英546537
浏览 71回答 2
2回答

MYYA

循环遍历一个部分中的 DIV,并附加该 DIV,后跟第二部分中的 DIV。第二个追加总是使用.first(),因为它从第二部分中删除第一个 DIV,因此下一个相应的 DIV 将是第一个。$(".first > div").each(function() {&nbsp; $(".merged").append(this);&nbsp; $(".merged").append($(".second > div").first());});<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script><section class="first">&nbsp; <div>One</div>&nbsp; <div>Two</div>&nbsp; <div>Three</div></section><section class="second">&nbsp; <div>Four</div>&nbsp; <div>Five</div>&nbsp; <div>Six</div></section><section class="merged"></section>

PIPIONE

这个决定是我做出的。这是一个javascript解决方案。forEach()使用方法:Array.from(sections_for_merge_section).forEach(function(sections_for_merge_sectionArray) {&nbsp;&nbsp; &nbsp;merged.append(sections_for_merge_sectionArray.cloneNode(true));});您需要在其中section添加合并的部分由代码添加:let merged = document.createElement('section');此外,该cloneNode(true)方法用于将数据复制到创建的部分中:...sections_for_merge_sectionArray.cloneNode(true)...window.onload = function() {&nbsp; let sections_for_merge = document.querySelector('.sections_for_merge');&nbsp; let sections_for_merge_section = document.querySelectorAll('.sections_for_merge section div');&nbsp; let merged = document.createElement('section');&nbsp;&nbsp;&nbsp; merged.className = 'merged';&nbsp; document.body.append(merged);&nbsp;&nbsp;&nbsp; Array.from(sections_for_merge_section).forEach(function(sections_for_merge_sectionArray) {&nbsp;&nbsp; &nbsp; merged.append(sections_for_merge_sectionArray.cloneNode(true));&nbsp; });&nbsp;&nbsp;}<div class="sections_for_merge">&nbsp; <section class="first">&nbsp; &nbsp;<div>One</div>&nbsp; &nbsp;<div>Two</div>&nbsp; &nbsp;<div>Three</div>&nbsp; </section>&nbsp; <section class="second">&nbsp; &nbsp;<div>Four</div>&nbsp; &nbsp;<div>Five</div>&nbsp; &nbsp;<div>Six</div>&nbsp; </section></div><br><p>Below is the created element <strong>div</strong> with merged divs:</p><br>
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript