Javascript 如何检查Tic Tac Toe赢家
我想知道我的代码有什么问题。我使用网站主体中的一张表和javascript制作了一个tic-tac-toe游戏。以下是我的代码的相关部分: 内体:Javascript 如何检查Tic Tac Toe赢家,javascript,html,dreamweaver,Javascript,Html,Dreamweaver,我想知道我的代码有什么问题。我使用网站主体中的一张表和javascript制作了一个tic-tac-toe游戏。以下是我的代码的相关部分: 内体: <body> </table> <table id="matrix" border="1"> <tr> <td class="cellCSS"> <img alt="Click Here" cla
<body>
</table>
<table id="matrix" border="1">
<tr>
<td class="cellCSS">
<img alt="Click Here" class="imageCSS" onclick="imageClicked(this,0,0)"/>
</td>
<td class="cellCSS">
<img alt="Click Here" class="imageCSS" onclick="imageClicked(this,0,1)"/>
</td>
<td class="cellCSS">
<img alt="Click Here" class="imageCSS" onclick="imageClicked(this,0,2)"/>
</td>
</tr>
...
</table>
</body>
您的问题是r==tbl.rows.length始终为false,因为for循环在r时迭代。您应该包含更多的imageClicked函数。我猜它开始了:
...
same = false;
var r = 0;
tbl = document.getElementById("matrix");
//alert(tbl.rows.length);
for(r = 0; r < tbl.rows.length; r++) {
// alert('Bob');
var _tempmg = tbl.rows[r].cells[col].childNodes[0].src;
alert(_tempmg);
if (!_tempmg) break;
if (_img.src != _tempmg) break;
same = true;
}
if (r == tbl.rows.length && same) {
alert(_img.src + "won");
return;
}
same = false;
...
在您发布的代码中:
function imageClicked(element, row, col) {
想必您之前已经声明了相同的内容以保持其本地性
same = false;
如果在循环中进行初始化,则无需在此处初始化r(即为其赋值)
var r = 0;
在for(…)表达式中添加一个条件可能更清楚,如:
if (_img.src != _tempmg) break;
same = true;
我需要查看imageClicked函数的更多内容,以了解它为什么不起作用。另一方面,您最好将数据存储在数组中,而不是存储在
中。它本身可能值得一看我的井字游戏。如果循环一直通过,也可以在r=tbl.rows.length处找到(即未调用break或在上一次迭代中调用break)
if (_img.src != _tempmg) break;
same = true;
for(r = 0; r < tbl.rows.length && !same; r++) {
if (_img.src == _tempmg) same = true;
}
if (r == tbl.rows.length && same) {
alert(_img.src + "won");
return;
}
same = false;