特定类出现后,Javascript在div中包装多个p标记

特定类出现后,Javascript在div中包装多个p标记,javascript,jquery,html,dom,Javascript,Jquery,Html,Dom,我想知道是否有可能在p tags class=“wrapAfterThisClass”中的特定类出现之后,用“wrapper”类将以下示例中的所有p标记包装在divs中 markeup是动态的,因此非常重要的是类“wrapAfterThisClass”,它是包装div的“触发器” 我来过accross solutions,建议在第n个数字后换行,但由于内容是动态的,所以类出现的时间间隔可能会有所不同 我的简化html标记如下所示: <p>1</p> <p class

我想知道是否有可能在p tags class=“wrapAfterThisClass”中的特定类出现之后,用“wrapper”类将以下示例中的所有p标记包装在divs中

markeup是动态的,因此非常重要的是类“wrapAfterThisClass”,它是包装div的“触发器”

我来过accross solutions,建议在第n个数字后换行,但由于内容是动态的,所以类出现的时间间隔可能会有所不同

我的简化html标记如下所示:

<p>1</p>
<p class="wrapAfterThisClass">2</p>
<p>3</p>
<p>4</p>
<p class="wrapAfterThisClass">5</p>
<p>6</p>
<p class="wrapAfterThisClass">7</p>
<div class="wrapper">
    <p>1</p>
    <p class="wrapAfterThisClass">2</p>
</div>
<div class="wrapper">
    <p>3</p>
    <p>4</p>
    <p class="wrapAfterThisClass">5</p>
</div>
<div class="wrapper">
    <p>6</p>
    <p class="wrapAfterThisClass">7</p>
</div>
1

2

三,

四,

5

六,

7

输出应如下所示:

<p>1</p>
<p class="wrapAfterThisClass">2</p>
<p>3</p>
<p>4</p>
<p class="wrapAfterThisClass">5</p>
<p>6</p>
<p class="wrapAfterThisClass">7</p>
<div class="wrapper">
    <p>1</p>
    <p class="wrapAfterThisClass">2</p>
</div>
<div class="wrapper">
    <p>3</p>
    <p>4</p>
    <p class="wrapAfterThisClass">5</p>
</div>
<div class="wrapper">
    <p>6</p>
    <p class="wrapAfterThisClass">7</p>
</div>

一,

2

三,

四,

5

六,

7

因此,我在jquery的每个循环中都尝试了slice.()和wrapAll(),但到目前为止运气都不好。 它给了我嵌套的包装,把它们都包起来

如果有人能给我指出正确的方向,我将不胜感激——但可能是我的方法错了

也许它甚至不是我需要的包装或切片

干杯比约恩

var a=[];
var a = [];

$("p").each(function(){
    a.push(this);

    if ($(this).hasClass("wrapAfterThisClass")) {
        $(a).wrapAll("<div class='wrapper'>");
        a = [];
    }
});
$(“p”)。每个(函数(){ a、 推(这个); if($(this).hasClass(“wrapAfterThisClass”)){ $(a).wrapAll(“”); a=[]; } });
var a=[];
$(“p”)。每个(函数(){
a、 推(这个);
if($(this).hasClass(“wrapAfterThisClass”)){
$(a).wrapAll(“”);
a=[];
}
});

您可以循环
.wrapAfterThisClass
元素,使用
prevAll('p')
获取前面的段落元素,然后
.addBack()
添加当前的
.wrapAfterThisClass
,然后只需
wrapAll()

$('.wrapAfterThisClass')。每个(函数(){
$(this.prevAll('p').addBack().wrapAll('');
} );

您可以循环
.wrapAfterThisClass
元素,使用
prevAll('p')
获取前面的段落元素,然后使用
.addBack()
添加当前的
.wrapAfterThisClass
,然后只使用
wrapAll()

$('.wrapAfterThisClass')。每个(函数(){
$(this.prevAll('p').addBack().wrapAll('');
} );

非常感谢:)非常感谢:)