使用javascript创建表并将ID和类添加到每个td [英] Creating table with javascript and add id and class to each td

查看:45
本文介绍了使用javascript创建表并将ID和类添加到每个td的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用JavaScript创建国际象棋游戏.我创建了一个棋盘,下一步是向创建的td添加一个ID和类.

I'm trying to create a chess game in javascript. I created a chessboard and the next step is to add an id's and classes to created td's.

这是代码:

<html>
    <head>
        <title> Play Chess! </title>
        <meta charset="utf-8">
        <link rel='stylesheet' href='css/styles.scss' type='text/css'/>
    </head>
    <body>
        <script>
            var table ='';
            var rows =8;
            var cols=8;
            for (var r = 0; r<rows;r++){
                table +='<tr>';
                    for(var c=0;c<cols;c++){
                        table+='<td>' +''+'</td>';
                    }
                table+='</tr>';
            }
            document.write("<table border=1>"+table+'</table>');
        </script>
    </body>
</html>

我知道我可以使用html来完成此操作,但是代码太多了,我相信还有其他方法可以做到这一点.

I know I can simply do this with html, but it's too much code and I belive there is other way to do this.

推荐答案

以下是使用纯JavaScript(无jQuery)的解决方案.将脚本放在结束</body>标记之前.这不使用document.write,这实际上是要避免的.而是HTML带有一个具有id属性的空表,然后通过脚本填充该表.

Here is a solution with plain JavaScript (no jQuery). Put the script just before the closing </body> tag. This does not use document.write which really is to be avoided. Instead the HTML has an empty table with an id attribute, which then is populated through script.

var rows =8;
var cols=8;
var table = document.getElementById('board');
for (var r = 0; r<rows; r++){
  var row = table.insertRow(-1);
  for (var c = 0; c<cols; c++){
    var cell = row.insertCell(-1);
    cell.setAttribute('id', 'abcdefgh'.charAt(c) + (rows-r));
    cell.setAttribute('class', 'cell ' + ((c+r) % 2 ? 'odd' : 'even'));
  }
}

table { 
    border-spacing: 0;
    border-collapse: collapse;
}
.cell { width: 20px; height: 20px; }
.odd { background-color: brown }
.even { background-color: pink }

<table id="board"></table>

作为奖励,它具有棋盘颜色的更改,并且id值从a1(左下)到h8(右上)

As a bonus it has the chessboard altering colors, and the id values are running from a1 (bottom-left) to h8 (top-right)

这篇关于使用javascript创建表并将ID和类添加到每个td的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆