首页 > 解决方案 > 无法使用函数在数组中定位 JS 生成的按钮,出现“无法读取属性 'setAttribute' of null”错误

问题描述

我只是想在单击时更改特定按钮的背景。我通过for循环生成了100个按钮(希望稍后制作一个简单的游戏)作为数组,同时分配一个id和一个不同的函数调用(基于循环的递增'i'值),并且我无法在单击时实际导致背景更改,而是出现以下错误“未捕获的 TypeError:无法在 HTMLButtonElement.onclick (index.html:15) 的 showOptions (brain.js:31) 处读取 null 的属性‘setAttribute’”

我的代码如下

var btn = [];
function generateBoard() {
  for (i = 0; i < 100; i++) {
    var modulo = i % 10;
    var up, forLeft;
    btn[i] = document.createElement("BUTTON");
    var element = document.getElementById("body");
    //btn[i].innerText = "CLICK ME";
    element.appendChild(btn[i]);
    btn[i].style.backgroundColor = "white";
    btn[i].id = i;
    btn[i].style.width = "50px";
    btn[i].style.height = "40px";
    btn[i].style.position = "absolute";
    btn[i].style.top = modulo * 100;
    btn[i].style.left = Math.floor(i / 10) * 100;
    btn[i].x = (i + 10) % 10;
    btn[i].y = Math.floor(i / 10);
    document
      .getElementById(btn[i].id)
      .setAttribute("onclick", "showOptions(i)");
    btn[i].innerText = btn[i].id;

    console.log(
      btn[i].id +
        " " +
        btn[i].style.left +
        " " +
        btn[i].style.top +
        " " +
        btn[i].x +
        " " +
        btn[i].y
    );
  }
}
generateBoard();
function showOptions(i) {
  document.getElementById(i).setAttribute("style", "background-color: red;"); //this is line 31
}

在 console.log 中,我实际上得到了正确的数字 btn[i].id,很奇怪。

错误的 (index.html:15) 行很简单

</html>

标签: javascripthtmlcssdom

解决方案


我已经修改了你的代码,修复了一些问题。我假设您有一个带有 id的元素,它与可以通过 访问的元素body不同。bodydocument.body

var buttons = [];

function generateBoard(){
    for(i = 0; i < 100; i++) {
        var modulo = i % 10;
        buttons[i] = document.createElement("BUTTON");
        document.getElementById("body").appendChild(buttons[i]);
        //buttons[i].innerText = "CLICK ME";
        buttons[i].style.backgroundColor = "white";
        buttons[i].id = i;
        buttons[i].style.width = "50px";
        buttons[i].style.height = "40px";
        buttons[i].style.position = "absolute";
        buttons[i].style.top = modulo * 100;
        buttons[i].style.left = Math.floor(i / 10) * 100;
        buttons[i].x = (i + 10) % 10;
        buttons[i].y = Math.floor(i / 10);
        buttons[i].addEventListener('click', function(event) {
            // This code is run when the button is clicked
            // Note I am passing the element, rather than an id
            showOptions(this);
        });
        buttons[i].innerText = i;

        console.log(buttons[i].id + " " + buttons[i].style.left + " " + buttons[i].style.top + " " + buttons[i].x + " " + buttons[i].y);
    }
}
generateBoard();
function showOptions(button){
    button.style.backgroundColor = "red";
}

推荐阅读