将一行单元格拆分为多行

时间:2013-01-08 08:22:11

标签: javascript html ajax

我从ajax调用请求了一些json数据,并将所有数据插入表中。现在作为下面的代码,所有数据都在一行单元格中,有没有办法循环遍历表并将其拆分成多行,每行包含4个单元格?

<div id="gallery">
    <table id="galleryTable"><tr></tr></table>
</div>


    $.ajax({
      type: "GET",
      dataType: "jsonp",
      cache: false,
      url: linkurl,
      success: function(data){

        paginate = data.pagination.next_url;
        var nextMaxId = data.pagination.next_max_id;
        console.log(nextMaxId);

        for(var i=0; i<15; i++){
          var instaPics = data.data[i].images.low_resolution.url;
          var avatar = data.data[i].user.profile_picture;
          var like = data.data[i].likes.count;
          var comment = data.data[i].comments.count;
          console.log(comment);                  

          $(#galleryTable tr').append('<td><img class="tagPics" src="'+instaPics+'"><a>'+like+"likes"
                                      +'</a><img class="avatar" src="'+avatar+'" height="20" width="20" /><a>'+comment+'</a></img></td>');
        }; 
      }          
    });

2 个答案:

答案 0 :(得分:2)

$.ajax({
      type: "GET",
      dataType: "jsonp",
      cache: false,
      url: linkurl,
      success: function(data){

        paginate = data.pagination.next_url;
        var nextMaxId = data.pagination.next_max_id;
        console.log(nextMaxId);
        var tr;
        for(var i=0; i<15; i++){
          var instaPics = data.data[i].images.low_resolution.url;
          var avatar = data.data[i].user.profile_picture;
          var like = data.data[i].likes.count;
          var comment = data.data[i].comments.count;
          console.log(comment);  
          if(i % 4 === 0){
             tr = $('<tr></tr>');
             $('#galleryTable').append(tr);
          } 


          tr.append('<td><img class="tagPics" src="'+instaPics+'"><a>'+like+"likes"
                                      +'</a><img class="avatar" src="'+avatar+'" height="20" width="20" /><a>'+comment+'</a></img></td>');
        }; 
      }          
    });

答案 1 :(得分:0)

Modulo(%)是你的朋友!这应该让你开始......

var row = '';
for(var i=0; i<15; i++) {
    // ...
    if( i > 0 && i % 4 == 0 ) {
        $('#galleryTable tr').append(row);
        row = '';
    }
    row += '<td> ...';
}
$('#galleryTable tr').append(row);