如何 select class 中的特定按钮标签

How to select a specific button tag inside of a class

我想做到这一点,当您单击按钮时,代码应该在 class 移动中提醒名称。但是我的代码不能正常工作,控制台显示 "Cannot read property 'getElementsByClassName' of undefined"。我的 javascript 代码有问题吗?谢谢

我的部分 javascript 代码;

for(var i=0; i<4; i++){
                document.getElementsByClassName("moves")[0].getElementsByTagName("BUTTON")[i].onclick
                = alert(document.getElementsByClassName("moves")[0].document.getElementsByClassName("move")[i].textContent);
}

我的部分 HTML 代码;

<div class="moves">
          <button>
            <span class="move">a</span> <span class="dp"></span>
            <img src="icons/fighting.jpg" alt="Pokemon move" />
          </button>
          <button>
            <span class="move">b</span> <span class="dp"></span>
            <img src="icons/fighting.jpg" alt="Pokemon move" />
          </button>
          <button>
            <span class="move">c</span> <span class="dp"></span>
            <img src="icons/fighting.jpg" alt="Pokemon move" />
          </button>
          <button>
            <span class="move">d</span> <span class="dp"></span>
            <img src="icons/fighting.jpg" alt="Pokemon move" />
          </button>
        </div>

有几点需要注意:

1 - 当您将 alert() 传递给点击处理程序时,它会立即被调用。您需要将其包装在一个函数中。

2 - 使用 this,您无需从最顶部重新选择元素,您可以从当前在范围内的位置开始。

for (var i = 0; i < 4; i++) {

  document.getElementsByClassName("moves")[0].getElementsByTagName("BUTTON")[i].onclick = function() {
    alert(this.textContent.trim())
  };
}
<div class="moves">
  <button>
            <span class="move">a</span> <span class="dp"></span>
            <img src="icons/fighting.jpg" alt="Pokemon move" />
          </button>
  <button>
            <span class="move">b</span> <span class="dp"></span>
            <img src="icons/fighting.jpg" alt="Pokemon move" />
          </button>
  <button>
            <span class="move">c</span> <span class="dp"></span>
            <img src="icons/fighting.jpg" alt="Pokemon move" />
          </button>
  <button>
            <span class="move">d</span> <span class="dp"></span>
            <img src="icons/fighting.jpg" alt="Pokemon move" />
          </button>
</div>