亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

無法使用函數在數組中定位 JS 生成的按鈕,出現“無法讀取屬性

無法使用函數在數組中定位 JS 生成的按鈕,出現“無法讀取屬性

胡子哥哥 2022-11-11 16:33:38
我只是想在單擊時更改特定按鈕的背景。我通過for循環生成了100個按鈕(希望稍后制作一個簡單的游戲)作為數組,同時分配一個id和一個不同的函數調用(基于循環的遞增'i'值),我無法在單擊時實際導致背景更改,而是出現以下錯誤:“未捕獲的 TypeError:無法在 HTMLButtonElement.onclick (index.html:15) 的 showOptions (brain.js:31) 處讀取屬性‘setAttribute’為 null”我的代碼如下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>
查看完整描述

3 回答

?
長風秋雁

TA貢獻1757條經驗 獲得超7個贊

我已經修改了你的代碼,修復了一些問題。我假設您有一個帶有 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";

}


查看完整回答
反對 回復 2022-11-11
?
小唯快跑啊

TA貢獻1863條經驗 獲得超2個贊

您的代碼存在多個問題。

你應該得到body帶有 的元素getElementsByTagName,它返回數組。所以選擇第一個元素。

設置 onclick 屬性應該使用inot text的值i。


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.getElementsByTagName("body")[0];

    //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

}


查看完整回答
反對 回復 2022-11-11
?
斯蒂芬大帝

TA貢獻1827條經驗 獲得超8個贊

您可以通過引用其自身的屬性來定位單擊的元素,而不是分配和嘗試使用 ID 屬性event。如果您要分析event(使用控制臺),您會注意到幾個屬性 -target允許訪問元素本身,這有助于簡化showOptions功能。在這種情況下,您也可以簡單地使用this從內部引用按鈕本身showOptions- 這將使其更加簡單 - 例如this.style.backgroundColor='red';


let bttns=[];


const generateBoard=function( s=100 ){

  const showOptions=function(e){

    e.target.style.backgroundColor='red';

  };


  for( let i=0; i < s; i++ ){

    /* create a new button and add properties */

    let bttn=document.createElement('button');

      bttn.setAttribute('id',i);

      bttn.setAttribute('data-x',((i+10)%10));

      bttn.setAttribute('data-y',Math.floor(i/10));


      bttn.style.left=( Math.floor( i / 10 ) * 100 )+'px';

      bttn.style.top=( ( i % 10 ) * 100 )+'px';

      bttn.style.width = '50px';

      bttn.style.height = '40px';

      bttn.style.position = 'absolute';

      bttn.innerText=i;


      /* bind event listener */

      bttn.addEventListener('click', showOptions );


    /* add to the DOM */

    document.body.appendChild( bttn );


    /* if it is important to have in an array... */

    bttns.push( bttn );

  }

}


document.addEventListener('DOMContentLoaded',(e)=>{

  generateBoard( 100 );

})


向元素添加任意屬性不是最佳實踐 - 而不是分配x,y您應該改用dataset屬性 - 所以data-x是data-y正確的。


查看完整回答
反對 回復 2022-11-11
  • 3 回答
  • 0 關注
  • 179 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號