jQuery:wrapAll但独立的元素集?
我有一个分组系统,两个 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>
问题类似于此 < a href="https://stackoverflow.com/questions/1527944/wrapall-jquery-problem">wrapAll jQuery 问题 但在这种情况下我们知道集合中的 div 数量,而在这种情况下我们不知道't。
有什么想法吗?
编辑:添加了 jsbin http://jsbin.com/ejepu3 的链接
I have a somewhat grouping system which all the elements between two divs are grouped together. See the code below to see what I'm trying to say:
$(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();
});
When the HTML is:
<div>[group]</div>
<div>first</div>
<div>second</div>
<div>[/group]</div>
it works just fine, but when there are two or more 'groups' the wrapAll wraps them together, for example:
<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>
The problem is similar to this wrapAll jQuery problem but in that case we know the number of divs in a set, while in this case we don't.
Any ideas?
Edit: added the link to jsbin http://jsbin.com/ejepu3
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我认为您只需要循环
groupo
的内容即可。另外,不需要使用filter()
。您可以使用:contains('')
选择器工作版本:http://jsfiddle .net/48Pfp/2/
I think you just needed to loop through the contents of
groupo
. Also, no need to usefilter()
. You can use the:contains('')
selectorworking version: http://jsfiddle.net/48Pfp/2/