0

我有一个分组系统,将两个 div 之间的所有元素组合在一起。请参阅下面的代码以了解我要说的内容:

$(document).ready(function(){
var groupo = $('div').filter(function(){return $(this).text().match(/\[group\]/)}); //finds "[group]"
var groupc = $('div').filter(function(){return $(this).text().match(/\[\/group\]/)}); //finds "[/group]"
groupc.addClass("groupclose"); //adds the class groupclose so that it can be used by nextUntil
 groupo.nextUntil(".groupclose").wrapAll('<div class="group"></div>');
 groupo.remove();
 groupc.remove();
});

当 HTML 为:

<div>[group]</div>
<div>first</div>
<div>second</div>
<div>[/group]</div>

它工作得很好,但是当有两个或多个“组”时 wrapAll 将它们包装在一起,例如:

<div>[group]</div>
<div>first</div>
<div>second</div>
<div>[/group]</div>

<div>[group]</div>
<div>this is in</div>
<div>another group</div>
<div>which get wrapped together with the one above</div>
<div>[/group]</div>

这个问题类似于这个wrapAll jQuery 问题,但在这种情况下,我们知道集合中 div 的数量,而在这种情况下我们不知道。

有任何想法吗?

编辑:添加到 jsbin http://jsbin.com/ejepu3的链接

4

1 回答 1

0

我认为您只需要遍历groupo. 此外,无需使用filter(). 您可以使用:contains('')选择器

var groupo = $("div:contains('[group]')");
var groupc = $("div:contains('[/group]')").addClass("groupclose");

$(groupo).each(function(){
    $(this).nextUntil(".groupclose").wrapAll('<div class="group"></div>');
});

groupo.remove();
groupc.remove();

工作版本:http: //jsfiddle.net/48Pfp/2/

于 2011-01-13T14:40:27.193 回答