简体   繁体   English

如何使用JavaScript和jQuery创建板NxN

[英]How to create board NxN using JavaScript and jQuery

I am trying to create board game (like chess board game) with JavaScript. 我正在尝试使用JavaScript创建棋盘游戏(如棋盘游戏)。

When I tried to do it this is what happened: 当我试图这样做时,这就是发生的事情:
在此输入图像描述

The <tr> got closed immediately with </tr> , same thing with <table> </table> <tr>立即用</tr>关闭,与<table> </table>
I tried to replace the append() method with appendTo() or add() but it didn't help 我试图用appendTo()add()替换append()方法,但它没有帮助

This is my JavaScript code: 这是我的JavaScript代码:

var boardSize = 5;

$(function() { //on load
    printBoard(boardSize);
});

function printBoard(i_BoardSize) {
    var maxRow = parseInt(i_BoardSize);
    var maxCol = parseInt(i_BoardSize);
    var num = 1;

    $("#board").append("<table oncontextmenu=\"return false\">");
    for(var row = maxRow - 1; row >= 0 ; row--) { 
           $("#board").append("<tr>");
            for(var col = 0; col < maxCol ; col++) {
                $("#board").append("<td>" + num + "</td>");
                num++;
            }

            $("#board").append("</tr>");
       }
        $("#board").append("</table>");
}

CSS: CSS:

td {
    width: 32px;
    height: 32px;
    cursor: pointer;
    text-align: center;
    border: 2px solid blue;
}

.redborder {
    background-color: red;
    color: white;
}

.blueborder {
    background-color: blue;
    color: white;
}

HTML: HTML:

<!DOCTYPE html>
<html>
    <head>
        <title>TODO supply a title</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <link rel='stylesheet' type='text/css' href='css/board.css' />
        <script type="text/javascript" src="jquery-2.1.1.min.js"></script>
        <script type="text/javascript" src="Scripts/board.js"></script>
    </head>
    <body>
        <p> <center><h3><font size="20" color="black"> Board Game</font></h3></center></p>
        <div>
            <div id="board">
                <div class="cell">
                </div>
            </div>
        </div>
    </body>
</html>

This happens because jQuery append() method not supporting only closing tags and trying to close tags if they wasn't closed in provided param. 发生这种情况是因为jQuery append()方法不支持关闭标记,并且如果它们未在提供的参数中关闭,则尝试关闭标记。 To solve this you need to assign your append() result to some variable, for example: 要解决此问题,您需要将append()结果赋给某个变量,例如:

var myTable = $("<table oncontextmenu=\"return false\"></table>").appendTo("#board");

and then append your rows to this var: 然后将行追加到此var:

var myRow = $("<tr></tr>").appendTo( myTable );

Same with columns: 与列相同:

myRow.append("<td>" + num + "</td>");

By using appendTo method you will be able to get newly created elements. 通过使用appendTo方法,您将能够获得新创建的元素。

So your final code should look like: 所以你的最终代码应如下所示:

var boardSize = 5;

$(function() { //on load
    printBoard(boardSize);
});

function printBoard(i_BoardSize) {
    var maxRow = parseInt(i_BoardSize);
    var maxCol = parseInt(i_BoardSize);
    var num = 1;

    var myTable = $("<table oncontextmenu=\"return false\"></table>").appendTo("#board");
    for (var row = maxRow - 1; row >= 0; row--) {
        var myRow = $("<tr></tr>").appendTo(myTable);
        for (var col = 0; col < maxCol; col++) {
            myRow.append("<td>" + num + "</td>");
            num++;
        }
    }
}

The others have supplied you with why this is happening but I thought I might give an example of how you might make better use of css and more recent dom usage. 其他人已经为您提供了为什么会这样,但我想我可能会举例说明如何更好地利用CSS和更新的dom用法。

Fiddle: http://jsfiddle.net/np62shu6/1/ 小提琴: http//jsfiddle.net/np62shu6/1/

But the basic idea is to define the number of cells, then write out a series of divs that have a 20% float value. 但基本思想是定义单元格数,然后写出一系列具有20%浮点值的div。 In the end you have a chess board with a cell data attribute. 最后你有一个具有单元格数据属性的棋盘。

HTML: HTML:

<div id="game">

</div>

CSS: CSS:

.cell{
    width:20%;
    float:left;
    text-align:center;
}

.odd{
 background:#eee;   
}

JS (assumed you place this in a load handler): JS(假设你把它放在一个加载处理程序中):

var cells = 25;
var cell;
var h;

for(var i = 1; i <= cells; i ++)
{
    cell = $('<div>').addClass('cell').attr('data-cell', i).text(i);
    if(i % 2 == 1)
        cell.addClass('odd');

    $('#game').append(cell);
}

h = $('.cell:last-of-type').width();
$('.cell').css({height: h, lineHeight: h + 'px'});

As others have said, append is a sequential method, so calling it one after the other will just keep dropping things in the DOM. 正如其他人所说的那样,append是一个顺序方法,所以一个接一个地调用它只会不断丢弃DOM。 But you can create elements, then add things to those elements using append, then use append to add that whole group to another... 但是你可以创建元素,然后使用append将元素添加到这些元素,然后使用append将整个组添加到另一个元素......

My example does not show this. 我的例子没有表明这一点。 My example is just an alternative to what you wrote. 我的例子只是你所写内容的替代品。 I would not do it the way you are doing it is all. 我不会按你所做的那样去做。

Another slight side note - chess boards have 64 cells (8 x 8), but I left it at 25 because your example did this. 另一个轻微的注意事项 - 国际象棋棋盘有64个单元格(8 x 8),但我把它留在了25,因为你的例子做到了这一点。

When you append a tag with jQuery it doesn't work like appending text to a HTML string. 当您使用jQuery附加标记时,它不会像将文本附加到HTML字符串那样起作用。 Instead it creates the dom element. 相反,它创建了dom元素。 Try something like this instead, notice the absence of closing tags and td is appended directly to the latest tr: 尝试这样的事情,注意没有结束标签,td直接附加到最新的tr:

var boardSize = 5;

$(function() { //on load
    printBoard(boardSize);
});

function printBoard(i_BoardSize)
{
    var maxRow = parseInt(i_BoardSize);
    var maxCol = parseInt(i_BoardSize);
    var num = 1;

    $("#board").append("<table oncontextmenu=\"return false\">");
    for(var row = maxRow - 1; row >= 0 ; row--)
       { 
           $("#board table").append("<tr>");
            for(var col = 0; col < maxCol ; col++)
             {
                 $("#board tr:last").append("<td>" + num + "</td>");
                num++;
            }
       }
}

 $(function() { //on load var boardSize = 5; printBoard(boardSize); }); function printBoard(i_BoardSize) { var maxRow = parseInt(i_BoardSize), maxCol = maxRow; var $table = $("<table oncontextmenu='return false'></table>").appendTo($("#board")); for(var row = 1; row <= maxRow; row++) { var $row = $("<tr/>").appendTo($table); for(var col = 1; col <= maxCol; col++) { $row.append("<td>" + (row*col) + "</td>"); } } } 
 td { width: 32px; height: 32px; cursor: pointer; text-align: center; border: 2px solid blue; } .redborder { background-color: red; color: white; } .blueborder { background-color: blue; color: white; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <p> <center><h3><font size="20" color="black"> Board Game</font></h3></center></p> <div> <div id="board"> <div class="cell"> </div> </div> </div> 

Side note: You don't have to append the closing tags manually... 附注:您不必手动附加结束标记...

The error is here: 错误在这里:

function printBoard(i_BoardSize)
{
var maxRow = parseInt(i_BoardSize);
var maxCol = parseInt(i_BoardSize);
var num = 1;

$("#board").append("<table oncontextmenu=\"return false\">");
for(var row = maxRow - 1; row >= 0 ; row--)
   {
      #here 
       $("#board").append("<tr>");
        for(var col = 0; col < maxCol ; col++)
         {
             #here
             $("#board").append("<td>" + num + "</td>");
            num++;
        }

        $("#board").append("</tr>");
   }
    $("#board").append("</table>");
}

You are appending each element to the #board instead of properly nesting them. 您将每个元素附加到#board而不是正确嵌套它们。 try keeping the created elements in variables, and do nesting: 尝试将创建的元素保存在变量中,并进行嵌套:

function printBoard(i_BoardSize)
{
var maxRow = parseInt(i_BoardSize);
var maxCol = parseInt(i_BoardSize);
var num = 1;

$tableelement = $("<table oncontextmenu=\"return false\"></table>");
$("#board").append($tableelement);
for(var row = maxRow - 1; row >= 0 ; row--)
   {
      #here 
       $rowelement = $("<tr></tr>");
       $tableelement.append($rowelement);
        for(var col = 0; col < maxCol ; col++)
         {
             #here
             $rowelement.append("<td>" + num + "</td>");
            num++;
        }
   }
}

Reason: certain browsers will immediately try to fix malformed HTML, and in the middle of the execution, the items are malformed while you insert it, and are wellformed after you finish. 原因:某些浏览器会立即尝试修复格式错误的HTML,并且在执行过程中,项目在插入时格式错误,并且在完成后表现良好。 in the middle -this function's execution is not atomic- the code is malformed and the browser tries to fix it by closing the tags you add. 在中间 - 这个函数的执行不是原子的 - 代码格式错误,浏览器试图通过关闭你添加的标签来修复它。 That's why you need to add elements by nesting -opening and closing the tags for them beforehand- 这就是为什么你需要通过嵌套 - 开启和关闭它们的标签来添加元素的原因 -

This is way easier and cleaner if you just learn JavaScript and work in the DOM. 如果您只是学习JavaScript并在DOM中工作,这会更简单,更清晰。

function makeBoardWithoutJQuery(xs, ys) {

    var table = document.createElement('table');
    var tbody = document.createElement('tbody');

    for (var y=0; y<ys; ++y) {
        var tr = document.createElement('tr');
        for (var x=0; x<xs; ++x) {
            var td = document.createElement('td');
            td.innerHTML = (y*xs) + x;
            tr.appendChild(td);
        }
        tbody.appendChild(tr);
    }

    table.appendChild(tbody);
    return table;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM