【问题标题】:Javascript wrap multiple p tags in div after a specific class appears出现特定类后,Javascript 在 div 中包装多个 p 标签
【发布时间】:2016-08-11 09:13:30
【问题描述】:

我想知道是否可以在 p 标签 class="wrapAfterThisClass" 中出现特定类之后将以下示例中的所有 p 标签包装在具有“包装器”类的 div 中。

标记是动态的,因此非常重要的是它是“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() 到目前为止没有运气。 它给了我嵌套的包装器来包装它们。

如果有人能指出我正确的方向,我将不胜感激 - 不过,这可能是我的方法错误。

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

比约恩干杯

【问题讨论】:

    标签: javascript jquery html dom


    【解决方案1】:
    var a = [];
    
    $("p").each(function(){
        a.push(this);
    
        if ($(this).hasClass("wrapAfterThisClass")) {
            $(a).wrapAll("<div class='wrapper'>");
            a = [];
        }
    });
    

    【讨论】:

      【解决方案2】:

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

      $( '.wrapAfterThisClass' ).each( function() {
          $( this ).prevAll( 'p' ).addBack().wrapAll( '<div class="wrapper" />' );
      } );
      

      Here's a fiddle

      【讨论】:

      • 非常感谢 :)
      猜你喜欢
      • 2016-09-04
      • 2015-04-20
      • 2021-02-16
      • 2015-06-20
      • 2017-05-04
      • 2019-04-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多