根据用户输入jQuery创建动态棋盘

时间:2016-08-04 02:23:22

标签: jquery dynamic html-table user-input

我正在编写一个编码挑战,要求我使用jQuery创建一个棋盘,以及一个输入表格,询问游戏板的大小(即6x6板,7x7板等)。无论何时输入是奇数(即7x7板,9x9板,11x11板),我都难以进行奇/偶类分配。如果在将输入#增加到任何奇数时运行JS小提琴,则奇数/偶数赋值会“跳过”。

$(document).ready(function() {
    
  //create input form for number/size of board
  $('h1').append('<div class=div1>Size of Board: <input type="text" id = "size1" name="size2" min = "2" max = "100" step = "2" value = "6"><input type="submit" id="submit1" value="Create"></div>')
 
  //create button to print Game Pieces 
  $('h1').append('<div><input type="submit" id="submitForm" value="Lets Play!"></div>');
  
  
  var z = '';
  //on clicking the button, create array of empty boxes/<td>
  $('#submit1').click(function() {
    var array = [];
    //remove previous appended array
    $('tbody').empty();

    //grab current value or size of gameboard
    z = $('#size1').val();
    
      //with a for loop, create "empty" table (z by z) of boxes
      for (var i=0; i<z; i++) {
        //addClass so we can grab later for color assignment
        var trEven = $('<tr>').addClass('trEven');
        var trOdd = $('<tr>').addClass('trOdd');
        //Differentiate between row to row: assign class trEven and trOdd to every other row      
        if (i%2 == 0) {
          array.push(trEven);
        }
        else {
          array.push(trOdd);
        }
        //for each row add z number of td's
          for (var j=0; j<z; j++) {
            array[i].append('<td></td>');
          }
      } 

    //append updated array to <tbody>
    $('tbody').append(array);
    //select all evens/odds of trOdd/trEven to assign colors using special selectors
    $('.trOdd td:odd').css('background-color', 'black'); 
    $('.trOdd td:even').css('background-color', 'white'); 
    $('.trEven td:odd').css('background-color', 'white');
    $('.trEven td:even').css('background-color', 'black'); 

  });//onclick function
  
  
  //Play Button: add game pieces
  $('#submitForm').click(function(){
    if (z <= 6) {
      //first two rows
      $('#gameBoard tr:eq(0) td:odd').append('<div class="gamePiece">')
      $('#gameBoard tr:eq(1) td:even').append('<div class="gamePiece">')
      //last two rows
      $('#gameBoard tr:last td:even').append('<div class="gamePiece">')
      $('#gameBoard tr:nth-last-child(2) td:odd').append('<div class="gamePiece">')
    }
    else if (z > 6) {
	  //first three rows
      $('#gameBoard tr:eq(0) td:odd').append('<div class="gamePiece">')
      $('#gameBoard tr:eq(1) td:even').append('<div class="gamePiece">')
      $('#gameBoard tr:eq(2) td:odd').append('<div class="gamePiece">')
      //last three rows
      $('#gameBoard tr:last td:even').append('<div class="gamePiece">')
      $('#gameBoard tr:nth-last-child(2) td:odd').append('<div class="gamePiece">')
      $('#gameBoard tr:nth-last-child(3) td:even').append('<div class="gamePiece">') 
    }

  })//onclick function
  
  
})//document
table {
  border: solid 1px black;
  border-spacing: 0px;
}
td {
  width: 50px;
  height: 50px;
}
.div1 {
  font-size: medium;
}
.gamePiece {
  border-radius: 100%;
  height: 100%;
  width: 100%;
  background-color: red;
}
<!DOCTYPE html>

<body>
  <h1>Game Board</h1>
  <table id="gameBoard">
    <tbody></tbody>
  </table>
  <script src="https://code.jquery.com/jquery-2.1.4.min.js"></script>
</body>

如果您拉起检查器工具并单击“跳过”行(例如第三行)并将其与第一行进行比较,则两行都被识别为“偶数”行,但第一个td元素不同。第1行的第一个td /“列”被拉为td:even。然而,第三行的第一个td /“列”被拉为td:odd。根据我的知识,似乎在每对行(1个奇数行和1个偶数行)之后索引跳过,当它应该为“0”时,第一列为“1”。这仅在电路板尺寸为奇数时发生。

有谁知道为什么要跳过索引?

2 个答案:

答案 0 :(得分:1)

关于CSS的全部内容。尝试从JS分配类到奇数和偶数元素,但使用CSS选择正确的元素。

&#13;
&#13;
$(document).ready(function() {

    //create input form for number/size of board
    $('h1').append('<div class=div1>Size of Board: <input type="text" id = "size1" name="size2" min = "2" max = "100" step = "2" value = "6"><input type="submit" id="submit1" value="Create"></div>')

    //create button to print Game Pieces 
    $('h1').append('<div><input type="submit" id="submitForm" value="Lets Play!"></div>');


    var z = '';
    //on clicking the button, create array of empty boxes/<td>
    $('#submit1').click(function() {
      var array = [];
      //remove previous appended array
      $('tbody').empty();

      //grab current value or size of gameboard
      z = $('#size1').val();

      //with a for loop, create "empty" table (z by z) of boxes
      for (var i = 0; i < z; i++) {
        //addClass so we can grab later for color assignment
        var trEven = $('<tr>').addClass('trEven');
        var trOdd = $('<tr>').addClass('trOdd');
        //Differentiate between row to row: assign class trEven and trOdd to every other row      
        if (i % 2 == 0) {
          array.push(trEven);
        } else {
          array.push(trOdd);
        }
        //for each row add z number of td's
        for (var j = 0; j < z; j++) {
          array[i].append('<td></td>');
        }
      }

      //append updated array to <tbody>
      $('tbody').append(array);
      //select all evens/odds of trOdd/trEven to assign colors using special selectors
      $('.trOdd td:odd').addClass('even');
      $('.trOdd td:even').addClass('odd');
      $('.trEven td:odd').addClass('odd');
      $('.trEven td:even').addClass('even');

    }); //onclick function


    //Play Button: add game pieces
    $('#submitForm').click(function() {
        if (z <= 6) {
          //first two rows
          $('#gameBoard tr:eq(0) td:odd').append('<div class="gamePiece">')
          $('#gameBoard tr:eq(1) td:even').append('<div class="gamePiece">')
            //last two rows
          $('#gameBoard tr:last td:even').append('<div class="gamePiece">')
          $('#gameBoard tr:nth-last-child(2) td:odd').append('<div class="gamePiece">')
        } else if (z > 6) {
          //first three rows
          $('#gameBoard tr:eq(0) td:odd').append('<div class="gamePiece">')
          $('#gameBoard tr:eq(1) td:even').append('<div class="gamePiece">')
          $('#gameBoard tr:eq(2) td:odd').append('<div class="gamePiece">')
            //last three rows
          $('#gameBoard tr:last td:even').append('<div class="gamePiece">')
          $('#gameBoard tr:nth-last-child(2) td:odd').append('<div class="gamePiece">')
          $('#gameBoard tr:nth-last-child(3) td:even').append('<div class="gamePiece">')
        }

      }) //onclick function


  }) //document
&#13;
table {
  border: 1px solid #000;
}

td {
  background-color: #fff;
  height: 50px;
  width: 50px;
}

td:nth-child(2n) {
  background-color: #000;
}

tr:nth-child(2n) td {
  background-color: #000;
}

tr:nth-child(2n) td:nth-child(2n) {
  background-color: #fff;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h1>Game Board</h1>
  <table id="gameBoard">
    <tbody></tbody>
  </table>
&#13;
&#13;
&#13;

答案 1 :(得分:1)

布尔标志如何确定您分配类的位置?

首先,在“创建”按钮单击处理程序中声明一个布尔变量:

var toggleFlag = true;

然后,在for循环中,您“计算”每行中td的数量,您可以立即指定一个类:

//for each row add z number of td's
for (var j = 0; j < z; j++) {
    if(toggleFlag){
        array[i].append('<td class="odd"></td>');
    }else{
        array[i].append('<td class="even"></td>');
    }
    // Toggle the flag for next iteration
    toggleFlag=!toggleFlag;
}

一旦这个循环结束,检查你是否应该在每一行上有一个奇数或偶数td ...因为如果它是奇数,你必须再次切换:

// If rows contain an even amout of td, toggle again before looping to next row
if(z % 2 == 0){
    toggleFlag=!toggleFlag;
}

最后,当您点击“让我们播放”按钮添加片段时,您可以使用奇数类而不是td:odd选择器选择:even

$('#gameBoard tr:nth-last-child(3) td.odd').append('<div class="gamePiece">')

See this working CodePen
;)

<小时/> 编辑解释初始错误

代码中的错误位于以下行:

$('.trOdd td:odd').css('background-color', 'black'); 
$('.trOdd td:even').css('background-color', 'white'); 
$('.trEven td:odd').css('background-color', 'white');
$('.trEven td:even').css('background-color', 'black'); 

这种逻辑适用于偶数量的正方形 但是如果数量很少,你就会致命地得到一个偏移量
这就是使这种“二乘二”分组效果的原因 所以你必须在每一行都有一个代码块的“交替逻辑” 这不是很简单 这就是为什么我通过在循环中分配循环td逐个循环的类来更快地解决问题的原因。

为了说明这一点,我做了another CodePen 它清楚地表明,此选择器$('.trOdd td:odd')选择了全部 td,其中奇数类在奇数tr ... 但不仅在一行上!就像我确定你在想......它不会像人类那样逐一获取行。它抓取所有表来收集匹配元素。

请参阅? 对于jQuery,只有两行(trOddtrEven)...
;)