簡體   English   中英

按鈕觸發周圍的按鈕無法正常工作

[英]Button triggering surrounding buttons not working properly

我有這個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 = 0時,才會切換按鈕i-1(左側的按鈕)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM