在javascript中创建顺序HTML数字

时间:2014-10-06 23:04:25

标签: javascript jquery

需要为生成的每四个项目创建一个html编号。

后端创建的项目没有特定的数量

<div class="item">item1 - pagination 1</div>
<div class="item">item2 - pagination 1</div>
<div class="item">item3 - pagination 1</div>
<div class="item">item4 - pagination 1</div>

<div class="item">item5 - pagination 2</div>
<div class="item">item6 - pagination 2</div>
<div class="item">item7 - pagination 2</div>
<div class="item">item8 - pagination 2</div>

<div class="item">item9 - pagination 3</div>
<div class="item">item10 - pagination 3</div>
<div class="item">item11 - pagination 3</div>
<div class="item">item12 - pagination 3</div>


<ul>
 // this html need generated by javascript
 <li class="pagination1">1<li>
 <li class="pagination2">2<li>
 <li class="pagination3">3<li>
<ul>

3 个答案:

答案 0 :(得分:4)

这样的事情应该让你开始:

var page = 0;

$('.item').each(function(i){
    if(i % 4 === 0){
        var $li = $('<li/>').prop({ class: 'pagination' + (++page) });
    }
});

http://jsfiddle.net/c87tsvo8/

答案 1 :(得分:0)

var c = Math.ceil(jQuery(".item").length / 4);

for (i = 0; i < c; i++) {
    jQuery("#ul-container").append('<li class="pagination' + (i + 1) + '">' + (i + 1) + '</li>');
}

答案 2 :(得分:0)

即使每组(.item)中的数字发生变化,这也应该有效:

    var
        IDs = [],
        ul = $('ul'),
        li = $('<li/>'),
        items = $('div.item').map(function(i,v) {
          return $(v).text().split(' ').pop().trim();
        }).get();
    $.each(items,function(i,v) {
      if( IDs.indexOf( v ) === -1 ) {
        IDs.push( v );
        ul.append( li.clone().addClass( 'pagination' + v ).text( v ) );
      }
    });

  $(document).ready(function() {
    var
        IDs = [],
        ul = $('ul'),
        li = $('<li/>'),
        items = $('div.item').map(function(i,v) {
          return $(v).text().split(' ').pop().trim();
        }).get();
    $.each(items,function(i,v) {
      if( IDs.indexOf( v ) === -1 ) {
        IDs.push( v );
        ul.append( li.clone().addClass( 'pagination' + v ).text( v ) );
      }
    });
  });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="item">item1 - pagination 1</div>
<div class="item">item2 - pagination 1</div>
<div class="item">item3 - pagination 1</div>
<div class="item">item4 - pagination 1</div>

<div class="item">item5 - pagination 2</div>
<div class="item">item6 - pagination 2</div>
<div class="item">item7 - pagination 2</div>
<div class="item">item8 - pagination 2</div>

<div class="item">item9 - pagination 3</div>
<div class="item">item10 - pagination 3</div>
<div class="item">item11 - pagination 3</div>
<div class="item">item12 - pagination 3</div>

<ul></ul>