我正在尝试创建一个简单的按钮事件,该事件设置一个类属性,该属性可以在100 td
个元素中为100 <tr>
个元素着色。元素在画布中创建,并设置为使用鼠标移动事件(如简单的绘图板)更改单元格的背景颜色。我不确定如何单独选择每个<td>
元素以将其所有属性设置为白色。我意识到这可能是非正统和多余的,但我需要在不久的将来为我自己的项目了解这一点。
<html>
<head>
<style>
#canvas { width: 500px;
border: 3px dashed #989898;
}
.blue { background-color: blue; }
.white { background-color: white; }
td { width: 3px; height: 3px; margin: 1px; padding: 1px; }
</style>
</head>
<body>
<table id = "myCanvas">
<caption>Draw Stuff Using Alt</caption>
<tbody id = "tbody"></tbody>
</table>
<button onclick="rectify()">The CLEARANCE BUTTON</button>
<script>
function makeCanvas()
{
var side = 100;
var bodyA = document.getElementById( "tbody" );
for ( var i = 0; i < side; ++i )
{
var row = document.createElement( "tr" );
for ( var j = 0; j < side; ++j )
{
var cell = document.createElement( "td" );
row.appendChild( cell );
}
bodyA.appendChild( row );
}
document.getElementById( "myCanvas" ).addEventListener(
"mousemove", detectMouse, false );
}
//////////////////////////////This is the function in question
function rectify()
{
var side = 100;
var row = document.getElementsByTagName( "tr" );
var cell = document.getElementsByTagName( "td" );
for ( var row = 0; i < side; ++i ){
row.childNodes( cell ).target;
for ( var j =0; j < side; ++i ){
for ( var j = 0; j < side; ++i ){
//if ( cell.attribute !== "white" ){
cell.setAttribute( "class", "white" );
//}
}
}
}
}
//////////////////////////////////////////////////////////////
function detectMouse( a )
{
if ( a.target.tagName.toLowerCase() == "td" )
{
if ( a.altKey )
{
a.target.setAttribute( "class", "blue" );
}
}
}
window.addEventListener( "load", makeCanvas, false );
</script>
</body>
</html>
答案 0 :(得分:0)
您可以使用document.querySelectorAll
简化此操作。有了这个功能,你不需要嵌套循环。它只适用于一个循环,因为你可以选择tr元素中的所有td元素。
function makeCanvas() {
var side = 100;
var bodyA = document.getElementById( "tbody" );
for ( var i = 0; i < side; ++i ) {
var row = document.createElement( "tr" );
for ( var j = 0; j < side; ++j ) {
var cell = document.createElement( "td" );
row.appendChild( cell );
}
bodyA.appendChild( row );
}
document.getElementById( "myCanvas" ).addEventListener("mousemove", detectMouse, false);
}
function rectify() {
var side = 100;
var cells = document.querySelectorAll('tr > td');
for ( var cellNo = 0; cellNo < cells.length; cellNo++ ){
cells[cellNo].setAttribute( "class", "white" );
}
}
//////////////////////////////////////////////////////////////
function detectMouse( a ) {
if ( a.target.tagName.toLowerCase() == "td" ){
if ( a.altKey ){
a.target.setAttribute( "class", "blue" );
}
}
}
window.addEventListener( "load", makeCanvas, false );
#canvas { width: 500px;
border: 3px dashed #989898;
}
.blue { background-color: blue; }
.white { background-color: white; }
td { width: 3px; height: 3px; margin: 1px; padding: 1px; }
<table id = "myCanvas">
<caption>Draw Stuff Using Alt</caption>
<tbody id = "tbody"></tbody>
</table>
<button onclick="rectify()">The CLEARANCE BUTTON</button>