我重新阅读了有关该主题的早期帖子,我认为我正确实施了它,直到它不起作用。有没有更好的方法来更改JavaScript中表格的行和列的元素?
来自HTML:
<table class="center" border="3" id="checkersBoard">...
<tr>
<td class="block"><img class="BlankSpace" src="Directory/BlankSpace.png"></td> <td class="block"><img class="RedPiece" src="Directory/RedPiece.png"></td> <td class="block"><img class="BlankSpace" src="Directory/BlankSpace.png"></td> <td class="block"><img class="RedPiece" src="Directory/RedPiece.png"></td> <td class="block"><img class="BlankSpace" src="Directory/BlankSpace.png"></td> <td class="block"><img class="RedPiece" src="Directory/RedPiece.png"></td> <td class="block"><img class="BlankSpace" src="Directory/BlankSpace.png"></td> <td class="block"><img class="RedPiece" src="Directory/RedPiece.png"></td>
</tr> // I know terrible but I was just copying and pasting from someone... will change later
来自JavaScript:
var board = document.getElementById("checkersBoard");
var isRedHighlighted = false;
var isBlackHighlighted = false;
var lastClick;
board.addEventListener("click", function(e)
{
if(isBlackHighlighted || isRedHighlighted)
{
if(isBlackHighlighted)
{
if(e.target.getAttribute('src') == "Directory/BlankSpace.png")
{
var targetLoc = {row :(e.target.parentNode.parentNode.rowIndex+1), col :(e.target.parentNode.cellIndex+1) };
var lastClickLoc = {row :(lastClick.parentNode.parentNode.rowIndex +1), col :(lastClick.parentNode.cellIndex +1) };
lastClick.src = "Directory/BlankSpace.png";
e.target.src= "Directory/BlackPiece.png";
if(lastClickLoc.row - 2 == targetLoc.row && lastClickLoc.col -2 == targetLoc.col)
{
alert('something should have happened');
board.rows[(lastClickLoc.row)].cells[(lastClickLoc.col)].setAttribute('src',"Directory/BlankSpace.png" ); // why does this not work
board.parentNode.rows[5].cells[5].src = "Directory/BlackPiece.png" // why does this not work
}
isBlackHighlighted = false;
}
答案 0 :(得分:1)
要访问给定row
和col
的元素,您可以使用:
board.getElementsByTagName('tr')[row].getElementsByTagName('td')[col]
所以你应该改变
board.rows[(lastClickLoc.row)].cells[(lastClickLoc.col)].setAttribute('src',"Directory/BlankSpace.png" );
board.parentNode.rows[5].cells[5].src = "Directory/BlackPiece.png"
到
board.getElementsByTagName('tr')[(lastClickLoc.row)].getElementsByTagName('td')[(lastClickLoc.col)].getElementsByTagName('img')[0].setAttribute('src',"Directory/BlankSpace.png" );
board.parentNode.getElementsByTagName('tr')[5].getElementsByTagName('td')[5].getElementsByTagName('img')[0].src = "Directory/BlackPiece.png"