Javascript:为函数中创建的表格的偶数行和偶数单元格着色

标签 javascript function colors cell

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

本质上,这里游戏的目的是让代码设置这样一种方式,即只有在偶数行和偶数单元格上,表格中的圆圈才会被涂成黄色,而其余的则保持绿色。

我现在的显示是这样的:

How it shows when previewing the HTML file

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

这是我的代码:

<!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。

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

最佳答案

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

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

上面的 CSS 规则匹配作为其父表 tr 的偶数子级的所有 td 元素,而 tr 本身又是其父表的偶数子级。

关于Javascript:为函数中创建的表格的偶数行和偶数单元格着色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59724001/

相关文章:

WPF 渲染颜色与画笔和控制元素的不透明度不一致

javascript - 成功和错误 Parse.User 回调均在 Parse.User.save() 上调用

javascript - 如何为移动设备自定义 addthis.com 分享/关注层以将其固定到页面末尾

javascript - Codemirror 自动完成 - 建议来源

javascript - 使用构造函数将对象插入数组?

c - 函数应该接受两个参数,一个数组和数组的大小

c - 递归混淆

java - 查找图像 OpenCV Android SDK 中的颜色百分比

javascript - Next.js - 理解 getInitialProps

android - 在 Android 4.4.2 : 上创建 TextInputLayout 时膨胀类 EditText 时出错