[英]Javascript wrap multiple p tags in div after a specific class appears
我想知道是否有可能在p标签class =“ wrapAfterThisClass”中添加特定类之后,将以下示例中的所有p标签都包装在divs中的“ wrapper”类中。
markeup是动态的,因此非常重要的是它是“ wrapAfterThisClass”类,它是将div包裹起来的“触发器”。
我遇到过各种解决方案,建议在第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>
因此,到目前为止,我在每个循环中都在jquery中尝试了slice。()和wrapAll(),但是没有运气。 它给了我所有包装的嵌套包装纸。
如果有人能指出正确的方向,我将不胜感激-不过,这可能是我的做法不对。
也许它甚至不需要包装或切片。
干杯比昂
var a = [];
$("p").each(function(){
a.push(this);
if ($(this).hasClass("wrapAfterThisClass")) {
$(a).wrapAll("<div class='wrapper'>");
a = [];
}
});
您可以循环.wrapAfterThisClass
元素,使用prevAll('p')
获取上一个段落元素,然后使用.addBack()
添加当前的.wrapAfterThisClass
,然后只需wrapAll()
:
$( '.wrapAfterThisClass' ).each( function() {
$( this ).prevAll( 'p' ).addBack().wrapAll( '<div class="wrapper" />' );
} );
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.