我可以使用jQuery .wrap或.wrapInner来包装一组不同的元素吗? [英] Can I use jQuery .wrap or .wrapInner to wrap around a set of different elements?

查看:65
本文介绍了我可以使用jQuery .wrap或.wrapInner来包装一组不同的元素吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆