用jQuery在两个h2标签之间包装一系列元素 [英] Wrapping a series of elements between two h2 tags with jquery

查看:76
本文介绍了用jQuery在两个h2标签之间包装一系列元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前有一个动态创建的页面,如下所示:

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包装h2p标记,直到下一个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屋!

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