【发布时间】:2018-12-09 23:30:59
【问题描述】:
我有这个 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();
};
我希望当我单击网格上的按钮时,它不仅会切换该按钮,还会切换顶部、底部、左侧和右侧按钮。
它对所有按钮都使用此代码,除非您切换边缘上的一个按钮。我需要它,例如,当您单击右侧边缘上的按钮时,它会与顶部、底部和左侧按钮一起切换。
如果您需要更多信息,请告诉我,谢谢!
【问题讨论】:
标签: javascript html