如何在jQuery中使用.wrapAll()?

问题描述 投票:2回答:1

我需要找到所有divs中的所有p标签和一类someClass并用另一个div包装它们。这是开头标记的样子:

<div class="someClass">
  // Lots of different tags generated by the site
  <p>Some text</p>
  <p>Some text</p>
  <p>Some text</p>
  <p>Some text</p>
</div>

<div class="someClass">
  // Lots of different tags generated by the site
  <p>Some text</p>
  <p>Some text</p>
</div>

会变成:

<div class="someClass">
  // Lots of different tags generated by the site
  <div class="bla">
    <p>Some text</p>
    <p>Some text</p>
    <p>Some text</p>
    <p>Some text</p>
  </div>
</div>

<div class="someClass">
  // Lots of different tags generated by the site
  <div class="bla">
    <p>Some text</p>
    <p>Some text</p>
  </div>
</div>

有任何想法吗?当我尝试使用.each():为每个div与一类someClass包装所有p标签,但它只是将它们全部包裹在顶部div

javascript jquery for-loop each wrapall
1个回答
3
投票

你试过这个吗?

$('div.someClass p').wrapAll(...);

或这个?

$('div.someClass').each(function() {
  $(this).find('p').wrapAll(...);
});

编辑

查看您发布的代码后,似乎是一个语法问题。你需要这行中的引号:

$(this).find('p').wrapAll(<div class='toggle'></div>);

它应该是:

$(this).find('p').wrapAll("<div class='toggle'></div>");
© www.soinside.com 2019 - 2024. All rights reserved.