javascript for in loop returning undefinded

后端 未结 1 1220
予麋鹿
予麋鹿 2021-01-28 12:40

Looking for help with a for in loop I am using in which returns undefined at the the end.

I have 26 buttons, one button for each letter in the alphabet. I need to scan

相关标签:
1条回答
  • 2021-01-28 12:57

    You should not use a for-in loop over a collection. If you do you need to test hasOwnProperty

    Instead use a simple loop

    var item = document.getElementsByClassName('button');
    // or better: var item = document.querySelectorAll('.button');
    for (var i=0;i<item.length;i++) {
      item[i].onclick = function(){
         console.log(this.value);
      };
    }
    

    var item = document.getElementsByClassName('button');
    // or better: var item = document.querySelectorAll('.button');
    for (var i = 0; i < item.length; i++) {
      item[i].onclick = function() {
        console.log(this.value);
      };
    }
    <div id="container">
      <header>
        <h1>Game</h1>
      </header>
    
      <div id="stage">
    
      </div>
    
      <div id="buttons">
        <input type="button" value="Q" id="Q" class="button">
        <input type="button" value="W" id="W" class="button">
        <input type="button" value="E" id="E" class="button">
        <input type="button" value="R" id="R" class="button">
        <input type="button" value="T" id="T" class="button">
        <input type="button" value="Y" id="Y" class="button">
        <input type="button" value="U" id="U" class="button">
        <input type="button" value="I" id="I" class="button">
        <input type="button" value="O" id="O" class="button">
        <input type="button" value="P" id="P" class="button"><br>
        <input type="button" value="A" id="A" class="button">
        <input type="button" value="S" id="S" class="button">
        <input type="button" value="D" id="D" class="button">
        <input type="button" value="F" id="F" class="button">
        <input type="button" value="G" id="G" class="button">
        <input type="button" value="H" id="H" class="button">
        <input type="button" value="J" id="J" class="button">
        <input type="button" value="K" id="K" class="button">
        <input type="button" value="L" id="L" class="button"><br>
        <input type="button" value="Z" id="Z" class="button">
        <input type="button" value="X" id="X" class="button">
        <input type="button" value="C" id="C" class="button">
        <input type="button" value="V" id="V" class="button">
        <input type="button" value="B" id="B" class="button">
        <input type="button" value="N" id="N" class="button">
        <input type="button" value="M" id="M" class="button">
      </div>
    </div>

    0 讨论(0)
提交回复
热议问题