我有这个 JavaScript 代码:
function toggle(i,j) {
b=document.getElementById("but_" + i + j)
t = b.innerHTML
if (t=="X") {b.innerHTML = "O";
b.setAttribute( "style", "color:red; background-color:yellow" )
}
if (t=="O") {b.innerHTML = "X";
b.setAttribute( "style", "color:white; background-color:black" )
}
}
function press(i, j) {
toggle(i, j);
toggle(i-1, j);
toggle(i+1, j);
toggle(i, j-1);
toggle(i, j+1);
}
function generateGrid() {
var d = document.getElementById("button-grid");
var table = document.createElement("table");
d.appendChild(table);
for (var i = 0; i < 5; i++) {
var row = document.createElement("tr");
for (var j = 0; j < 5; j++) {
var cell = document.createElement("td");
cell.innerHTML = "<button type=button id=but_" + i + j +
" onclick=\"press(" +i + ',' +j + ")\"" +
" style=\"color:red; background-color:yellow\"" +
">O</button>" ;
row.appendChild(cell);
}
table.appendChild(row);
}
toggle(2,2) // Set middle button to off state (otherwise it seems to be impossible).
}
window.onload = function() {
generateGrid();
};
我希望当我单击网格上的按钮时,它不仅会切换该按钮,还会切换顶部、底部、左侧和右侧的按钮。
此代码适用于所有按钮,除非您切换边缘的按钮。我需要它,例如,当您单击右侧边缘上的按钮时,它会与顶部、底部和左侧按钮一起切换。
如果您需要更多信息,请告诉我,谢谢!
最佳答案
您必须添加一个 if 语句来检查按钮是否位于边缘 - 例如,您可以使用:
if (i > 0) {
toggle(i-1, j);
}
if (i < 4) {
toggle(i+1, j);
}
if (j > 0) {
toggle(i, j-1);
}
if (j < 4) {
toggle(i, j+1);
}
这样,只有当按钮 i-1(左侧的按钮)不在左列上或者 i = 0 时,才会切换该按钮。
关于javascript - 按钮触发周围按钮无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53697761/