如何在 jQuery 中包装一组重复的元素?

发布于 2024-08-31 07:18:09 字数 527 浏览 6 评论 0原文

在 jQuery 中,我如何用 div 包装一组可重复的元素?

例如我有:

img
h4
p  
img
h4
p
img
h4
p

我需要用 div class="container"imgh4p 设置代码>.所以它看起来像:

<div class="container"> img h4 p </div>
<div class="container"> img h4 p </div>
<div class="container"> img h4 p </div>

我不断嵌套 div.containers

In jQuery how would I go about wrapping a repeatable set of elements with a div?

For example I have:

img
h4
p  
img
h4
p
img
h4
p

I need to wrap each img, h4, p set with a div class="container". So it will look like:

<div class="container"> img h4 p </div>
<div class="container"> img h4 p </div>
<div class="container"> img h4 p </div>

I keep getting nested div.containers!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

日暮斜阳 2024-09-07 07:18:09

你可以做这样的事情:

var elems = $("#content").find("img, h4, p");
for(var i = 0; i < elems.length; i+=3) {
  elems.slice(i, i+3).wrapAll("<div class='container'></div>");
}

这通过选择这些元素所在的容器并获取这个特定类型来工作,如果你想要的元素是一切,你可以替换 .find(selector).children(),在本例中我将其用作父元素:

<div id="container"></div>

您可以在此处查看工作演示

You can do something like this:

var elems = $("#content").find("img, h4, p");
for(var i = 0; i < elems.length; i+=3) {
  elems.slice(i, i+3).wrapAll("<div class='container'></div>");
}

This works by selecting the container these elements are in and grabbing this specific types, if the elements you want are everything, you can replace .find(selector) with .children(), in this case I used this for the parent element:

<div id="container"></div>

You can see a working demo here

小耗子 2024-09-07 07:18:09

您的示例非常简单,因此这将有效:

$("h4").each(function () {
  $(this).prev().andSelf().next().andSelf().wrapAll("<div class='container'/>");
});

此处演示

Your example is pretty simple, so this will work:

$("h4").each(function () {
  $(this).prev().andSelf().next().andSelf().wrapAll("<div class='container'/>");
});

demo here

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文