如何将div包含在同一个类元素的多个中 [英] How to wrap div around multiple of the same class elements

查看:77
本文介绍了如何将div包含在同一个类元素的多个中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将多个相同的类div包装成div并跳过不具有相同类的div。 .wrap不会将它们组合在一起,而.wrapAll会抛出下面的非类别div。我一直在试图创建一个替代解决方案,但没有用。

I'm trying to wrap multiple same class divs into a div and to skip divs not with the same class. .wrap doesn't combine them, and .wrapAll throws the non-classed divs underneath. I've been tinkering around with attempts to create an alternate solution but with no avail.

原文:

<div class="entry">Content</div>
<div class="entry">Content</div>
<div class="entry">Content</div>
<div>Skip in wrap</div>
<div class="entry">Content</div>
<div class="entry">Content</div>
<div class="entry">Content</div>

    continued...

通缉结果:

<div>
    <div class="entry">Content</div>
    <div class="entry">Content</div>
    <div class="entry">Content</div>
</div>
<div>Skip in wrap</div>
<div>
    <div class="entry">Content</div>
    <div class="entry">Content</div>
    <div class="entry">Content</div>
</div>


推荐答案

你可以快速循环通过< div> 使用进行循环的元素。在下面的代码中,只需在此处更改初始选择器以获取所有这些兄弟节点div,例如 #content> div.entry 或无论它们在哪里:

You can loop pretty quickly through your <div> elements using a for loop. In the below code, just change the initial selector here to grab all those siblings divs, e.g. #content > div.entry or wherever they are:

var divs = $("div.entry");
for(var i=0; i<divs.length;) {
  i += divs.eq(i).nextUntil(':not(.entry)').andSelf().wrapAll('<div />').length;
}​

你可以在这里尝试一下。我们只是使用 .entry < div> 元素/api.jquery.com/nextUntil/\"rel =noreferrer> .nextUntil() 获取所有 .entry 元素,直到有一个非 .entry 一个使用 :not() selector 。然后我们将采用下一个元素,加上我们开始使用的元素( .andSelf() )并执行 .wrapAll()<该组的/ code> 。在他们被包裹之后,我们正在跳过循环中的许多元素。

You can give it a try here. We're just looping through, the .entry <div> elements using .nextUntil() to get all the .entry elements until there is a non-.entry one using the :not() selector. Then we're taking those next elements, plus the one we started with (.andSelf()) and doing a .wrapAll() on that group. After they're wrapped, we're skipping ahead either that many elements in the loop.

这篇关于如何将div包含在同一个类元素的多个中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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