首页 > 解决方案 > Javascript:在函数中创建的表格的均匀行甚至单元格着色

问题描述

目前我的 JS 函数有点问题。

本质上,这里游戏的目的是让代码设置为仅在偶数行和偶数单元格上,表格中的圆圈将被着色为黄色,而其余的则保持绿色。

我现在有这样的显示:

预览 HTML 文件时的显示方式

圆圈周围的红色方块表示需要用黄色而不是绿色着色的偶数行/偶数单元格。

这是我的代码:

<!DOCTYPE html>
<html lang="en" dir="ltr">

<head>
    <style>
        body {
            background-color: linen;
        }

        td {
            height: 75px;
            width: 75px;
            background-color: green;
            border-radius: 50%;
            display: inline-block;
        }
    </style>
    <meta charset="utf-8">
    <title></title>
    <script type="text/javascript">
        function validation() {
            var userSubmit = document.getElementById('size').value; //takes the users input and stores it within the variable userSubmit.
            var num_rows = userSubmit; //assigning the users input to the number of rows.
            var num_cols = userSubmit; //assigning the users input to the number of colums.
            var tableBody = ""; //empty string setup for the table.

            for (var r = 0; r < num_rows; r++) {
                tableBody += "<tr>"; //for loop going through the number of rows required to complete the table.
                for (var c = 0; c < num_cols; c++) {
                    tableBody += "<td>" + c + "</td>"; //for loop, within the rows for loop, this is to determine the number of columns required in the table
                }
                tableBody += "</tr>";
            }
            document.getElementById('wrapper').innerHTML = ("<table>" + tableBody + "</table>");
        }
    </script>
</head>

<body>
    <form name="form1">
        <select id="size">
            <option value="3">3x3</option>
            <option value="5">5x5</option>
            <option value="7">7x7</option>
        </select>
    </form>
    <button type="submit" onclick="validation()">Generate Graph</button>

    <div id="wrapper"></div>
</body>

</html>

我的功能是从用户选择的网格中创建表格,但我不确定如何处理如上所述为所需的单元格着色所需的 JS。

任何建议将不胜感激,或者如果我不够清楚,请告诉我!

标签: javascriptfunctioncolorscell

解决方案


使用嵌套的 CSS 选择器,您可以为偶数行和偶数列上的单元格着色。

tr:nth-child(even) td:nth-child(even) {
  background-color: red;
}

上面的 CSS 规则匹配所有 td 元素,它们是其父 tr 的偶数子元素,它本身是其父表的偶数子元素。


推荐阅读