在jQuery循环中连接循环?

时间:2013-08-19 15:54:21

标签: javascript jquery

我正在尝试创建类似网格的结构。我想在循环中创建一个循环,并根据它是列还是行来附加div。以下是我的 attempt

for (var row = 0; row < 8; row++) {
    $('#board').append('<div class="row">'+ row +'</div>');  
}

我想用简单的Javascript复制(代码很可能不正确,我只是想展示一个我想要的例子):

var board = document.getElementById('board');

for (var row = 0; row < 8; row++) {
    board.write('<div class="row">');
    for(var col = 0; col < 8; col++) {
        var row = document.getElementsByClassName('row');
        row.write('<div class="piece">'+col+'</div>')
    }
    board.write('</div>');
}

如果我能以某种方式复制document.write()中的jQuery方法,那将会非常有用。当我试图包含一个forloop时,.append()对我不起作用。

3 个答案:

答案 0 :(得分:2)

你只需要循环遍历行然后单元格来构建一个单独的html字符串,而不是只附加一次:

var rows = [], cells = [];
for (var row = 0; row < 8; row++) {
    cells = [];
    for (var cell = 0; cell < 8; cell++) {
        cells.push('<div class="piece">'+ row +'</div>');
    }
    rows.push('<div class="row">' + cells.join('') + '</div>');
}

$('#board').html(rows.join(''));

DEMO HERE

答案 1 :(得分:1)

尝试以下操作 - 如果您需要更具体地操作DOM,请使用JQuery

var board = document.getElementById('board'),
    html = '';

for (var row = 0; row < 8; row++) {
    html += '<div class="row">';
    for(var col = 0; col < 8; col++) {
        html += '<div class="piece">'+col+'</div>';
    }
    html += '</div>';
}

board.innerHTML = html;

或者使用JQuery:

var board = $('#board');
...
board.append($(html));

答案 2 :(得分:1)

据我所知,您希望最终得到这样的结构:

<div id="board">
  <div class="row">
    <div class="piece"></div>
    <div class="piece"></div>
    <div class="piece"></div>
    (...)
  </div>
  (...)
</div>

我们假设您已经有一个董事会(<div id="board"></div>)。

for( var row = 0; row < 8; row++ ) {
  //Create a row
  $row = $('<div class="row"></div>');

  //Stuff 8 pieces in that row
  for( var col = 0; col < 8; col++ ) {
    $row.append( $('<div class="piece">' + col + '</div>') );
  }

  //Add the row to the board
  $('#board').append( $row );
}

编辑:在您的情况下,您甚至可以将其简化为:

//Stuff 8 rows in the board
for( var row = 0; row < 8; row++ ) {
  $('#board').append( $('<div class="row"></div>') );
}

//Stuff 8 pieces in every of the 8 rows
//This can be done because the piece is the same for every row
for( var col = 0; col < 8; col++ ) {
  $('.row').append( $('<div class="piece">' + col + '</div>') );
}

jsFiddle:http://jsfiddle.net/3jGnF/