我可以使用jQuery .wrap或.wrapInner来包装一组不同的元素吗? [英] Can I use jQuery .wrap or .wrapInner to wrap around a set of different elements?
问题描述
我有这样的HTML结构:
I have a HTML structure like so:
<section>
<item>
<ele class="blue" />
<ele class="green" />
<ele class="red" />
</item>
<item>
<ele class="blue" />
<ele class="green" />
<ele class="red" />
</item>
<item>
<ele class="blue" />
<ele class="green" />
<ele class="red" />
</item>
</section>
我需要在新的div中将后两个元素包装在每个<item>
内,以便看起来像这样:
I need to wrap the second two elements inside each <item>
in a new div, so that it looks like the following:
<item>
<ele class="blue" />
<div class="extra-wrapper">
<ele class="green" />
<ele class="red" />
</div>
</item>
是否可以使用任何jQuery wrap
函数来实现这一目标?还是有另一种方式,而不必筛选每个项目,在其中找到匹配的元素,构建新的HTML字符串并将其放回去?
Is it possible to use any of the jQuery wrap
functions to achieve this? Or is there another way, without having to filter through each item, find the matching elements within, build a new string of HTML and put them back in?
推荐答案
要做到这一点,您可以遍历每个.blue
元素,获取以下所有同级元素,并在其上调用wrapAll()
,如下所示:
To do this you can loop over each .blue
element, get all the following siblings and call wrapAll()
on them, like this:
$('.blue').each(function() {
$(this).nextAll().wrapAll('<div class="extra-wrapper"></div>');
});
.extra-wrapper {
border: 1px solid #C00;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<section>
<div>
<div class="blue">blue</div>
<div class="green">green</div>
<div class="red">red</div>
</div>
<div>
<div class="blue">blue</div>
<div class="green">green</div>
<div class="red">red</div>
</div>
<div>
<div class="blue">blue</div>
<div class="green">green</div>
<div class="red">red</div>
</div>
</section>
请注意,我将<ele />
和<item />
元素更改为div,因为它们是非标准的.
Note that I changed the <ele />
and <item />
element to divs as they were non-standard.
这篇关于我可以使用jQuery .wrap或.wrapInner来包装一组不同的元素吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!