【问题标题】:Button triggering surrounding buttons not working properly按钮触发周围按钮无法正常工作
【发布时间】: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


    【解决方案1】:

    您必须添加一个 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(左侧的按钮)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-01-31
      • 1970-01-01
      • 2013-11-11
      • 2017-03-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多