0

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

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. .append()当我尝试包含一个 forloop 时,我无法正常工作。

4

3 回答 3

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

在这里演示

于 2013-08-19T16:02:48.737 回答
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));
于 2013-08-19T16:03:02.703 回答
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/

于 2013-08-19T16:04:56.400 回答