jQuery获取下一组类?

时间:2011-10-13 17:46:43

标签: jquery next closest

我有以下HTML

<body>
   <div class="myCool">blah</div>
   <div class="cool">some text</div>
   <div class="cool">some text</div>
   <div class="cool">some text</div>
   <div class="cool">some text</div>
   <div class="myCool">blah</div>
   <div class="cool">some text</div>
   <div class="cool">some text</div>
   <div class="cool">some text</div>
   <div class="cool">some text</div>
</body>

我要做的是从myCool开始,然后将其包含在接下来的4个班cooldiv?所以它看起来像

 <div id="1" class="myWrapped">
   <div class="myCool">blah</div>
   <div class="cool">some text</div>
   <div class="cool">some text</div>
   <div class="cool">some text</div>
   <div class="cool">some text</div>
 </div>
 <div id="2" class="myWrapped">
   <div class="myCool">blah</div>
   <div class="cool">some text</div>
   <div class="cool">some text</div>
   <div class="cool">some text</div>
   <div class="cool">some text</div>
 </div>

我有什么想法可以做到这一点吗?

2 个答案:

答案 0 :(得分:4)

$(".myCool").each(function(i){
  $(this).nextUntil(".myCool").andSelf().wrapAll("<div id='" + (i+1) + "' class='myWrapped'></div>");
});

答案 1 :(得分:-2)

你可以这样做

jQuery("<div class='myCool'>blah</div>").appendTo('body');
for(var i=0; i<4;i++)
{
    jQuery('<div class="cool">some text</div>').appendTo('.myCool');
}