为什么 btn.addEventListener 不是函数。我陷入了这个问题,找不到任何解决方案。任何人都可以帮助我吗?

why btn.addEventListener is not a function. i am stuck in this problem and couldn't find any solution .anyone can help me?

** 我正在学习 Dom 操作,这是我的第二天... 我怎样才能将它作为一个函数来生成我已经存储在我的数组中的随机颜色索引。 **

const btn = document.getElementsByClassName("btn");
const color = document.getElementsByClassName("color")


btn.addEventListener('click', function() {
  const randomNumber = getRandomNumber();

  document.body.style.backgroundColor = colors[randomNumber]
  color.textContent = color[randomNumber]
})


function getRandomNumber() {
  return Math.floor(Math.random() * colors.length);
}
<div class="btn">Click Me </div>

getElementsByClassName returns 一个数组,而不是单个 DOM 对象。您可以尝试向元素添加一个 id 并使用 getElementById

getElementsByClassName return 元素数组(参见 doc)。

要获取第一个元素,您应该获取数组的第一个元素 document.getElementsByClassName("btn")[0]; 或向按钮添加一个 id 并使用 document.getElementById('myButton') 函数

获取它

const btn = document.getElementsByClassName("btn")[0];
const color = document.getElementsByClassName("color")


btn.addEventListener('click', function() {
  const randomNumber = getRandomNumber();

  document.body.style.backgroundColor = colors[randomNumber]
  color.textContent = color[randomNumber]
})


function getRandomNumber() {
  return Math.floor(Math.random() * colors.length);
}
<div class="btn">Click Me </div>

getElementsByClassName 将 return 一个类似对象的数组 dom 元素匹配 class。您需要 select 您要定位的数组中的条目:

const btn = document.getElementsByClassName("btn")[0];

详见here