使用jQuery从DIV中的列表中包装元素集

时间:2013-12-04 21:51:49

标签: javascript jquery each

我有一个很长的名单,每个名字都会包含在span个标签中。

示例:

<span>Yang Zajicek</span>
<span>Daniela Athey</span>
<span>Alanna Bumpers</span>
<span>Audry Waldron</span>
<span>Agnes Wininger</span>
<span>Tarah Mandelbaum</span>
<span>Dedra Paille</span>
<span>Codi Morrone</span>
<span>Shan Huntoon</span>
<span>Silas Zerangue</span>
<span>Thalia Saleh</span>
<span>Britt Spurlock</span>
<span>Miguelina Dasilva</span>
<span>Scott Scholz</span>
<span>Judith Badura</span>
<span>Alfredia Kidder</span>
<span>Jae Doty</span>
<span>Charise Blakeslee</span>
<span>Yen Axelson</span>
<span>Aurora Cochran</span>
<span>Lavina Crete</span>
<span>Monique Pate</span>
<span>Lady Edelstein</span>
<span>Clark Summitt</span>
<span>Milagros Whetstone</span>
<span>Tracy Tokarski</span>
<span>Wendolyn Crafts</span>
<span>Sandra Clyde</span>
<span>Alyse Giltner</span>
<span>Glennis Roos</span>

现在需要的是我必须经历它们,如循环或使用each(),我需要用<div class="row"></div>包装这些组。我对wrap()和基本循环非常熟悉,但是我遇到了太多错误,试图确定包装时间和位置模式的逻辑。

包装的模式如下:

  • 浏览所有跨度,将它们分成5组和6组, 重复此模式直到所有包裹。除了上面提到的类之外,还要添加第二个类到与项目数相关的每个div

最终结果,无论我开始使用多少个跨度:

<div class="row five">
  <span>Yang Zajicek</span>
  <span>Daniela Athey</span>
  <span>Alanna Bumpers</span>
  <span>Audry Waldron</span>
  <span>Agnes Wininger</span>
</div>
<div class="row six">
  <span>Tarah Mandelbaum</span>
  <span>Dedra Paille</span>
  <span>Codi Morrone</span>
  <span>Shan Huntoon</span>
  <span>Silas Zerangue</span>
  <span>Thalia Saleh</span>
</div>
<div class="row five">
  <span>Britt Spurlock</span>
  <span>Miguelina Dasilva</span>
  <span>Scott Scholz</span>
  <span>Judith Badura</span>
  <span>Alfredia Kidder</span>
</div>
<div class="row six">
  <span>Jae Doty</span>
  <span>Charise Blakeslee</span>
  <span>Yen Axelson</span>
  <span>Aurora Cochran</span>
  <span>Lavina Crete</span>
  <span>Monique Pate</span>
</div>
<div class="row five">
  <span>Lady Edelstein</span>
  <span>Clark Summitt</span>
  <span>Milagros Whetstone</span>
  <span>Tracy Tokarski</span>
  <span>Wendolyn Crafts</span>
</div>
<div class="row six">
  <span>Sandra Clyde</span>
  <span>Alyse Giltner</span>
  <span>Glennis Roos</span>
</div>

最后一行可以包含1-6个项目,这些项目会有所不同,但是类名称必须遵循“第五行”或“第六行”的模式。 CSS将适应这一结果。

1 个答案:

答案 0 :(得分:5)

这是一个解决方案:

http://jsfiddle.net/QWHYK/

while ($('#list > span').length) {
    $('#list > span:lt(5)').wrapAll('<div class="row five" />');
    $('#list > span:lt(6)').wrapAll('<div class="row six" />');
}

你可以通过一点缓存改进它,但逻辑就在那里。