javascript - Javascript:在函数中创建的表格的均匀行甚至单元格着色
问题描述
目前我的 JS 函数有点问题。
本质上,这里游戏的目的是让代码设置为仅在偶数行和偶数单元格上,表格中的圆圈将被着色为黄色,而其余的则保持绿色。
我现在有这样的显示:
圆圈周围的红色方块表示需要用黄色而不是绿色着色的偶数行/偶数单元格。
这是我的代码:
<!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 规则匹配所有 td 元素,它们是其父 tr 的偶数子元素,它本身是其父表的偶数子元素。
推荐阅读
- css - CSS grid layout: force fixed layout
- java - 如何在 ApplicationRunner 中正确访问安全的 Spring Data REST 存储库?
- php - 无法声明类 App\Http\Controllers\CalendarController,因为该名称已在使用中
- security - 如果来自同一来源的多个 HTTP 响应的内容安全策略不同,浏览器如何响应
- kubernetes - 无法使用 nginx 入口访问在内部负载均衡器上公开的服务
- ruby-on-rails - 我的 Rails 嵌套模型无法识别 _destroy 属性
- javascript - 带有加载程序的 Vuetify 按钮继续处于加载状态
- c# - 将两个 PDF 页面合并为一个页面?
- python - Django REST 框架:POST 请求:仅在数据不存在时如何保存数据
- ruby - 尝试检查我的 Hash 中的内容,但收到“未定义的方法 `&' for Hash”错误