用javascript重构html

时间:2013-10-27 09:26:04

标签: javascript jquery dom jquery-1.4

我有一个常规的无序链接列表,我想用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。

3 个答案:

答案 0 :(得分:2)

DEMO

$('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');

Reftrences

答案 1 :(得分: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/

答案 2 :(得分: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/