【问题标题】:jQuery Get the Next Set of Classes?jQuery 获取下一组类?
【发布时间】:2011-10-13 17:46:43
【问题描述】:

我有以下 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 个类 cool 包装成 div ?所以看起来像

 <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>

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

【问题讨论】:

标签: jquery next closest


【解决方案1】:

试试

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

【讨论】:

  • 不错的解决方案,不过忘记了 ID!
  • 你先生 - 是一个传奇!谢谢 - 我缺少的是.andSelf() :) 添加id 也是首选吗?怎么样.each(function(i)} ..... &lt;div id="' + i + '" ...
  • @KevinB - 只是一个问题 - 如果我只想为 1 "set" 做这件事?我该怎么办?即从.mycool.cool x4 但没有第二个等,即需要喜欢使用 .next('cool')` 之类的东西来获得 4x 或其他东西或?
  • @Andy - 不要使用.each$(".myCool").nextUntil(".myCool").etc...
  • @KevinB - 感谢您的回复!不,但我的意思是 - 如果我没有下一个 .myCool - 即我只有 .myCool, .cool x4
【解决方案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');
}

【讨论】:

  • -1 根本不回答问题
猜你喜欢
  • 2013-01-31
  • 1970-01-01
  • 1970-01-01
  • 2011-05-13
  • 1970-01-01
  • 2013-05-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多