如何合并具有相同类的两个div-jQuery [英] How to combine two divs that have the same class - jQuery
问题描述
我有这样的div结构
<div class="items">
<div class="itemRow">
<div class="item">
<div class="item">
<div class="item">
</div>
<div class="itemRow">
<div class="item">
<div class="item">
<div class="item">
</div>
</div>
如何使它们合并/合并两个div"itemRow"?像这样
How can I make them merge/combine the two divs "itemRow"? to be like this
<div class="items">
<div class="itemRow">
<div class="item">
<div class="item">
<div class="item">
<div class="item">
<div class="item">
<div class="item">
</div>
</div>
使用jQuery
推荐答案
首先,您的itemRow>项目没有结束标记.
First of all, your itemRow > item(s) have no closing tag.
您需要做的是遍历所有具有相同类的元素,并将第一个作为基础,然后将具有相同类的其他元素的子代附加到基础元素:
What you need to do is go through all of the elements with same class save the first as a base one, and then append the children of the other elements with same class to the base element:
var endelement;
$.each($('.itemRow'), function(index, value) {
if (index == 0)
endelement = $(this).clone();
else
{
$.each($(this).children('.item'), function(i, v){
$(this).clone().appendTo(endelement);
});
}
});
$('.endProduct').html(endelement[0].outerHTML);
通过这种方式,您可以将最终结果作为单独的变量获取,并且可以随心所欲地使用它,而原始元素保持原样.
This way you get the end result as seperate variable and you can do with it whatever you want, while the original elements stay as they were.
我在这里创建了一个小提琴: http://jsfiddle.net/dejvidpi/qEBZ4/
I've created a fiddle here: http://jsfiddle.net/dejvidpi/qEBZ4/
这篇关于如何合并具有相同类的两个div-jQuery的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!