jquery包装相邻元素的组

我有一个允许用户在页面上插入内容块的cms。 用户可以使用不同类型的内容块,它们可以按任何顺序插入。 高级dom结构的示例可能如下所示:

Some rich text

...
...
...

Some more rich text

Lorem ipsum

...
...

我想要做的是在包装’容器’div中包装任何相邻的’box’div。 因此,在上面的示例中,将插入两个“容器”div,因为有两组box div,导致:

 

Some rich text

...
...
...

Some more rich text

Lorem ipsum

...
...

我不认为有一个聪明的方法来使用css选择器,所以有人知道无论如何用jQuery做到这一点?

那么你可以像我刚刚掀起的这个JSFiddle例子那样做。

这基本上循环遍历每个.box将其添加到数组并确定下一个元素是否也具有.box类:

 var collection = []; $('.box').each(function() { var nextBox = $(this).next().hasClass('box'); ... collection.push($(this)); }) 

如果下一个元素没有 .box类,它会创建包含分隔符,在collection数组中第一个.box之前将其放在页面上,然后使用appendTo将所有.box分隔.box移动到其中:

  if(!nextBox) { var container = $('
'); container.insertBefore(collection[0]); for(i=0;i

小提琴在这里: http : //jsfiddle.net/jdelight/XutA6/5/这是一个使用css的可能解决方案,它允许您使用单个背景颜色和边框设置块的样式。 HTML将是这样的:

  
this is block 1
this is block 2
this is block 3
this is block 4
this is block 5

CSS将是:

  /* style all blocks with the required background colour and border */ .block { background: #eee; color: #000; border: 1px solid red; border-bottom: 0; padding: 20px; width: 400px; border-radius: 20px; /* remove the rounded corners from he bottom left/right */ border-bottom-left-radius:0; border-bottom-right-radius:0; position: relative; } /* style all adjacent blocks and remove the radius - so the top block has a radius and the others don't */ .block + .block { border-radius: 0; border-top: 0; } /* create a cheeky block with content after which sits below all blocks */ /* so it's hidden from all the blocks above it apart from the very bottom one (see bottom: -10px) */ /* then style the rounded corners on that one */ .block::after { content:'.'; display: block; background: red; height: 10px; position: absolute; border-bottom: 1px solid red; border-left: 1px solid red; border-right: 1px solid red; bottom: -10px; width: 440px; background: #eee; left:-1px; border-bottom-left-radius:10px; border-bottom-right-radius:10px; } 

您可以使用

  1. .nextUntil ,获取所有下一个.box
  2. .andSelf将当前元素添加到集合中
  3. .wrapAll将每个集合包装到另一个.container
 $('.box').not('.box+.box').each(function(){ $(this).nextUntil(':not(.box)').addBack().wrapAll('
'); });
  

Some rich text

...
...
...

Some more rich text

Lorem ipsum

...
...