【问题标题】:How to wrap DIV tags with different class names? [duplicate]如何用不同的类名包装 DIV 标签? [复制]
【发布时间】:2019-04-24 17:45:16
【问题描述】:

重复:
How can I add a parent element to a group of paragraph?

我在文档中重复了以下 HTML 块

<!-- first block -->
<div class="first">
   My first div
</div>
<div class="second">
   My second div
</div>

<!-- second block -->
<div class="first">
   My first div
</div>
<div class="second">
   My second div
</div>

...

如何使用 jQuery 包装 Div 以获得这样的 HTML...

<!-- first block -->
<div class="container">
   <div class="first">
      My first div
   </div>    
   <div class="second">
      My second div
   </div>
</div>

<!-- second block -->
<div class="container">
   <div class="first">
      My first div
   </div>    
   <div class="second">
      My second div
   </div>
</div>

...

【问题讨论】:

  • 您的编辑明显改变了问题。 wrapAll 仍然是您的做法,这取决于您如何选择要包装的内容。我已经更新了my answer,提供了两个方法示例,具体取决于您的块的组织方式。即使您的特定结构碰巧不适合任何一个示例,这也应该可以让您指出正确的方向。

标签: javascript jquery dom parent-child jquery-traversing


【解决方案1】:

你很幸运,这正是wrapAll 的用途:

$(".first, .second").wrapAll('<div class="container"></div>');

Live Example | Source


您的编辑明显改变了问题。如果您只需要在 within 一些包含块中执行上述操作,则可以遍历包含块并将 wrapAll 仅应用于其内容。您需要一种方法来确定您想要对 div 进行分组的方式,而您没有在问题中指定。

如果 div 周围有某种容器,您可以这样做:

$(".block").each(function() {
  $(this).find(".first, .second").wrapAll('<div class="container"></div>');
});

在该示例中,我假设 div 位于类 "block" 的容器中。

Live Example | Source

如果没有识别它们的结构性方法,您将不得不以其他方式进行。例如,在这里我们假设任何时候看到first,我们都应该停止分组:

var current = $();

$(".first, .second").each(function() {
  var $this = $(this);
  if ($this.hasClass('first')) {
    doTheWrap(current);
    current = $();
  }
  current = current.add(this);
});
doTheWrap(current);

function doTheWrap(d) {
  d.wrapAll('<div class="container"></div>');
}

Live Example | Source

因为$() 为您提供文档顺序中的元素,所以如果我们按顺序循环它们,保存它们,然后每当我们看到一个新的@ 987654339@(当然,最后清理一下),你会得到想要的结果。

或者这是做同样事情的另一种方法,它不使用wrapAll。它依赖于 first 匹配的元素是 first(所以在 firsts 之前没有 seconds!):

var current;

$(".first, .second").each(function() {
  var $this = $(this);
  if ($this.hasClass('first')) {
    current = $('<div class="container"></div>').insertBefore(this);
  }
  current.append(this);
});

Live Example | Source

【讨论】:

  • 哦...我不知道 wrapAll... +1
  • 是的,我的编辑正在改变问题,所以我重新发布了这个问题,我在stackoverflow.com/questions/13878539/… jQuery 的一行代码中得到了另一个智能解决方案
  • 很好的例子,非常有用。
  • @Max:谢谢!很高兴有帮助! (我没有看到任何“单行”答案,FWIW。)
【解决方案2】:
$('div').wrapAll('<div class="container" />');

会这样做,但这也会包装任何其他 div,所以也许:

$('.first, .second').wrapAll('<div class="container" />'); 

更好。

【讨论】:

  • 不,wrap单独包装它们。 (每个都会有自己的容器 div。)
  • wrap() 和 wrapAll() 不起作用:wrap() 方法包装每个 Div,而 wrapAll() 将所有块包装在一起。我需要一个函数来包装每个块...
  • 这将是因为您没有具体说明您想要什么,现在已经更改了您的问题!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-12-04
  • 1970-01-01
  • 2018-08-30
  • 1970-01-01
  • 1970-01-01
  • 2021-06-27
  • 2011-05-21
相关资源
最近更新 更多