用JavaScript设计棋盘

时间:2016-10-24 16:06:10

标签: chess

我想用JavaScript打印棋盘。但输出不是必需的。但控制台打印正确。但是网页的输出是不同的。

我的另一个问题是为什么我不能使用&#34; \ n&#34;通过javascript代码在网页中添加新行? Javascript理解\ n为新行,html为<br />。我应该在JavaScript中使用什么?

&#13;
&#13;
var chessBoard = function (length, black) {
    var result = "";
    for (var line = 1; line <= length; line++) {
        for (var pair = 1; pair <= length; pair++) {
            result += " " + black; //\xa0\xa0\xa0
        }
        result += "<br />";
        for (var pair2 = 1; pair2 <= length; pair2++) {
            result += black + " "; //\xa0\xa0\xa0
        }
        result += "<br />";        
    }

    console.log(result);
    return result;
}

document.getElementById("testid").innerHTML = chessBoard(4, "#");
&#13;
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>test</title>

</head>

<body>

    <div id="testid">Hello, here will be the pattern!</div>

    <script src="Script1.js" type="text/javascript"></script>
</body>
</html>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:0)

我不确定你想要什么,但要在输入时显示文字,请使用前缀:

HTML:     

<html>
    <head>
        <meta charset="utf-8">
        <title>test</title>
    </head>

    <body>
        <pre id="testid">Hello, here will be the pattern!</pre>
        <script src="Script1.js" type="text/javascript"></script>
    </body>

</html>

JS:

var board = "";
for (var y=0; y<8; y++) {
    for (var x=0; x<8; x++) {
        board += '#';
    }
    board += "\n";
}
console.log(board);
document.getElementById("testid").innerHTML = board;