我正在尝试为自己创建一个时间表站点,以练习CSS网格和Javascript,我希望能够选择“已完成?”时间表部分,并将div的颜色更改为绿色。但是,我没有运气..到目前为止,我的代码是:
document.getElementsByClassName('tick').onclick = changeBgColor;
function changeBgColor() {
document.getElementsByClassName('tick').style.backgroundColor = "green";
}
<div class="item tick complete1"></div>
<div class="item tick complete2"></div>
<div class="item tick complete3"></div>
<div class="item tick complete4"></div>
<div class="item tick complete5"></div>
<div class="item tick complete6"></div>
<div class="item tick complete7"></div>
任何帮助将不胜感激!! 谢谢!
答案 0 :(得分:0)
您需要遍历所有元素以添加click
事件侦听器。也可以使用this.style.background = "green";
来更改background
函数内部的click
颜色。
var elem = document.getElementsByClassName('tick');
for(var i=0; i<elem.length; i++){
elem[i].addEventListener('click', changeBgColor);
}
function changeBgColor() {
this.style.background = "green";
}
<div class="item tick complete1">1</div>
<div class="item tick complete2">2</div>
<div class="item tick complete3">3</div>
<div class="item tick complete4">4</div>
<div class="item tick complete5">5</div>
<div class="item tick complete6">6</div>
<div class="item tick complete7">7</div>
答案 1 :(得分:0)
document.getElementsByClassName
返回一个collection。使用spread operator
进行转换后,在此collection中循环。使用forEach遍历此数组,并使用addEventListener添加click事件
[...document.getElementsByClassName('tick')].forEach(function(item) {
item.addEventListener('click', changeBgColor)
})
function changeBgColor() {
this.style.backgroundColor = "green";
}
<div class="item tick complete1">1</div>
<div class="item tick complete2">2</div>
<div class="item tick complete3">3</div>
<div class="item tick complete4">4</div>
<div class="item tick complete5">5</div>
<div class="item tick complete6">6</div>
<div class="item tick complete7">7</div>