【问题标题】:How can I wrap each element and all its siblings before the next occurrence of the same element?如何在下一次出现相同元素之前包装每个元素及其所有兄弟?
【发布时间】:2013-09-11 21:37:17
【问题描述】:

我有一些类似于以下的标记:

<h3>A Heading</h3>
<p>Here is a paragraph.</p>

<ul>
  <li>First</li>
  <li>Second</li>
</ul>

<blockquote>Here's some other block-level element</blockquote>

<h3>The Wrapping Should Stop Before This Heading, but a Second One Should Begin</h3>
<ol>
  <li>First</li>
  <li>Second</li>
</ol>

<p>Notice the varying block-level elements? It probably doesn't make any difference.</p>

我想将每个h3 以及直到下一个h3 的所有内容都包含在一个div 中。

结果应该是:

<div>
  <h3>A Heading</h3>
  <p>Here is a paragraph.</p>

  <ul>
    <li>First</li>
    <li>Second</li>
  </ul>

  <blockquote>Here's some other block-level element</blockquote>
</div>

<div>
  <h3>The Wrapping Should Stop Before This Heading, but a Second One Should Begin</h3>
  <ol>
    <li>First</li>
    <li>Second</li>
  </ol>

  <p>Notice the varying block-level elements? It probably doesn't make any difference.</p>
</div>

我发现了类似的问题,例如this one。它使用.nextUntil().andSelf() 的组合(或.addBack() 一旦我的编辑被批准),但这会将h3s 和separate divs 之间的内容包装起来.

【问题讨论】:

    标签: javascript jquery selector siblings wrapall


    【解决方案1】:

    您需要:first 选择器,否则您将包装所有内容,而不仅仅是第一个h3到第二个h3

    $('h3:first').nextUntil('h3').addBack().wrapAll('&lt;div&gt;');

    Fiddle

    【讨论】:

    • 没错。对于我的特定用例,我得到了所有这些,但为了简单起见,问题中没有说明。
    【解决方案2】:

    似乎.wrapAll() 是缺少的链接。

    $('h3').nextUntil('h3').addBack().wrapAll('<div>');
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-10-02
      相关资源
      最近更新 更多