0

我有一个常规的无序列表链接,我想用 js 改变它

<ul>
  <li><a href="#">Theme 1</a></li>
  <li><a href="#">Theme 2</a></li>
  <li><a href="#">Theme 3</a></li>
  <li><a href="#">Theme 4</a></li>
  <li><a href="#">Theme 5</a></li>
  <li><a href="#">Theme 6</a></li>
  <li><a href="#">Theme 7</a></li>
  <li><a href="#">Theme 8</a></li>
  <li><a href="#">Theme 9</a></li>
  <li><a href="#">Theme 10</a></li>
  <li><a href="#">Theme 11</a></li>
  <li><a href="#">Theme 12</a></li>
</ul>

我想要以下输出:

<div class="themes__row">
  <div class="themes__item><a href="#">Theme 1</a></div>
  <div class="themes__item><a href="#">Theme 2</a></div>
  <div class="themes__item><a href="#">Theme 3</a></div>
  <div class="themes__item><a href="#">Theme 4</a></div>
</div>
<div class="themes__row">
  <div class="themes__item><a href="#">Theme 5</a></div>
  <div class="themes__item><a href="#">Theme 6</a></div>
  <div class="themes__item><a href="#">Theme 7</a></div>
  <div class="themes__item><a href="#">Theme 8</a></div>
</div>
<div class="themes__row">
  <div class="themes__item><a href="#">Theme 9</a></div>
  <div class="themes__item><a href="#">Theme 10</a></div>
  <div class="themes__item><a href="#">Theme 11</a></div>
  <div class="themes__item><a href="#">Theme 12</a></div>
</div>

我来回尝试了几种不同的解决方案,但最终变得非常混乱,所以我真的没有任何代码可以显示。这是如何巧妙地完成的?如果这很重要,该站点正在使用 jQuery 1.4.4。

4

3 回答 3

2

演示

$('ul').each(function () {
    var lis = $('li', this);
    for (var i = 0; i < lis.length; i += 4) {
        lis.slice(i, i + 4).wrapAll('<div class="themes__row"></div>');
    }
    $('.themes__row li').replaceWith(function () {
        return '<div class="themes__item">' + this.innerHTML + '</div>';
    });
}).contents().unwrap('ul');

参考文献

于 2013-10-27T09:45:59.820 回答
0

你可以使用这样的东西:

var items = $("ul li a");
var parent = items.eq(0).closest("ul"), cntr = 0;
for (var i = 0; i < items.length / 4; i++) {
    var container = $('<div class="themes__row"></div>');
    for (var j = 0; j < 4; j++) {
        $('<div class="themes__item"><a href="#">' + items.eq(cntr++).html() + '</a></div>').appendTo(container);
    }
    $(document.body).append(container);
}
parent.remove();

工作演示:http: //jsfiddle.net/jfriend00/7zWt9/

于 2013-10-27T09:34:47.097 回答
0

您可以使用以下代码:

var target = $('ul');
var elems = target.children('li').contents(); //get li contents

for (var i = 0; i < elems.length; i++) {
    var elem = document.createElement('div');
    elem.className = 'themes__item';
    elem.appendChild(elems[i]); //wrap contents in divs

    //append divs to rows
    if (i % 4 == 0) { //if elem index is multiple of 4
        //create a new row and add elem
        $('<div class="themes__row">').insertBefore(target).append(elem); 
    } else {
        target.prev().append(elem); //else append elem to existing row
    }
}
target.remove(); // remove ul

在这里看到它http://jsfiddle.net/valentin/u6LkM/3/

于 2013-10-27T10:36:03.570 回答