【问题标题】:How to use .wrapAll() in jQuery?如何在 jQuery 中使用 .wrapAll()?
【发布时间】:2010-12-06 17:32:05
【问题描述】:

我需要在所有divs 中找到所有带有someClass 类的p 标签,并用另一个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(): 对于每个divsomeClass 类时,包装所有p 标签,但它只是将它们全部包装在顶部div

【问题讨论】:

标签: javascript jquery for-loop each wrapall


【解决方案1】:

你试过了吗?

$('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>");

【讨论】:

  • 我已经尝试过类似的事情。现在真的很头疼!!我已经发布了一个问题的例子:pastebin.me/30acb260acc142dd0c9979aca9812390
  • @John - 您的代码几乎可以工作,只需将&lt;div&gt; 类更改为someClass。这是一个工作演示 - jsbin.com/oxexe/edit 添加到 URL 以查看代码
  • @Russ:我不确定你的意思。编辑的部分是对他代码中的一行的修改,他在其中插入了“切换”div。不应将其更改为“someclass”。
  • @John - 检查您的选择器中 &lt;div&gt; 的 CSS 类与问题的 HTML 页面中已经存在的 &lt;div&gt; 的 CSS 类的情况 - 您有 @987654332 @ 而问题是someClass。根据 HTML 4.01 规范,类和名称区分大小写(尽管某些浏览器不符合规范) - devedge-temp.mozilla.org/viewsource/2001/css-class-id
  • 啊。我没有测试过它,也没有打算让它值得复制粘贴。不过,感谢您指出这一点。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-11-23
  • 2011-12-31
相关资源
最近更新 更多