用jQuery在两个h2标签之间包装一系列元素 [英] Wrapping a series of elements between two h2 tags with jquery
问题描述
我目前有一个动态创建的页面,如下所示:
I currently have a page being dynamically created like below:
<h2>a Heading</h2>
<p>a paragraph</p>
<p>a paragraph</p>
<p>a paragraph</p>
<p>a paragraph</p>
<p>a paragraph</p>
<h2>a Heading</h2>
<p>a paragraph</p>
<p>a paragraph</p>
<p>a paragraph</p>
<p>a paragraph</p>
<p>a paragraph</p>
我要做的是使用jQuery包装h2
和p
标记,直到下一个h2
标记:例如:
What I'm looking to do is to use jQuery to wrap the h2
and p
tags till the next h2
tag: e.g.:
<div class="headingName">
<h2>a Heading</h2>
<p>a paragraph</p>
<p>a paragraph</p>
<p>a paragraph</p>
<p>a paragraph</p>
<p>a paragraph</p>
</div>
<div class="headingName">
<h2>a Heading</h2>
<p>a paragraph</p>
<p>a paragraph</p>
<p>a paragraph</p>
<p>a paragraph</p>
<p>a paragraph</p>
</div>
到目前为止,我没有成功地对此进行管理,但是已经在这里使用了来自用户的代码(找不到原始文章的链接)已经接近:
So far I unsuccessfully managed this, but have gotten close using code from a user here (can't find the link to the original article):
$('.report-content h2').each(function(){
var $set = $();
var nxt = this.nextSibling;
while(nxt) {
if(!$(nxt).is('.report-content h2')) {
$set.push(nxt);
nxt = nxt.nextSibling;
} else break;
}
$set.wrapAll('<div class="content" />');
});
我得到的是div
仅被包裹在p
标记周围,但需要包括相关的h2
标记,通常是p
标记上方的标记.
What I get is the div
being wrapped around only the p
tags but need to include the associated h2
tag, usually the one above the p
tags.
推荐答案
获取每个h2
,获取所有同级项,直到获得另一个h2
(或该级别没有元素),然后重新包含h2
在集合中. 这是JSFiddle.
Take each h2
, grab all sibilings until you get another h2
(or there are no elements at this level) and then reinclude the h2
in the set. Here's the JSFiddle.
$('.report-content h2').each(function(){
$(this)
.nextUntil("h2")
.addBack();
.wrapAll('<div class="content" />');
});
jQuery文档
- nextUntil
- addBack
- wrapAll
这篇关于用jQuery在两个h2标签之间包装一系列元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!