【问题标题】:why btn.addEventListener is not a function. i am stuck in this problem and couldn't find any solution .anyone can help me? [duplicate]为什么 btn.addEventListener 不是函数。我陷入了这个问题,找不到任何解决方案。任何人都可以帮助我吗? [复制]
【发布时间】:2021-12-23 17:36:23
【问题描述】:
** 我正在学习 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 将返回一个类似结构的数组,即HTMLCollection,因此您必须使用索引来获取元素为btn[0].addEventListener...,您可以在HTMLCollection 上添加eventListener,但在HTMLElements 上。你应该阅读docs
-
标签:
javascript
html
css
dom-events
dom-manipulation
【解决方案1】:
getElementsByClassName 返回一个元素数组(参见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>
【解决方案2】:
getElementsByClassName 将返回一个类似于类的 dom 元素对象的数组。您需要在此数组中选择要定位的条目:
const btn = document.getElementsByClassName("btn")[0];
详情请见here
【解决方案3】:
getElementsByClassName 返回一个数组,而不是单个 DOM 对象。您可以尝试向元素添加 id 并使用 getElementById