该脚本不起作用js-单击"添加类",然后单击"删除类"



任务-当你点击圆圈时,它应该变成红色。再次按下应该会返回到原始状态。似乎一切都是正确的,表明,但脚本不起作用,帮助。控制台错误-";消息":"未捕获的类型错误:favorite.addEventListener不是函数"-为什么?

const favorite = document.querySelectorAll('.clothes__item-favorite');
favorite.addEventListener('click', function() {
favorite.classList.toggle("favorite--active");
});
body {
background-color: #000;
}
.clothes__item-favorite {
display: block;
position: absolute;
background-color: #fff;
width: 2.3rem;
height: 2.3rem;
border-radius: 100%;
left: 1.25rem;
top: 1.25rem;
font-size: 0;
transition: 0.3s;
cursor: pointer;
}
.clothes__item-favorite:hover {
background-color: #fc7a7a;
}
.favorite--active {
background-color: #fc7a7a;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<i class="clothes__item-favorite">Добавить в избранное</i>
</body>
</html>

这是因为您使用的是.querySelectorAll()。请改用.querySelector(),因为您只选择了一个元素。querySelectorAll选择一个集合。下面的代码应该可以工作。

//changed querySelectorAll to querySelector
const favorite = document.querySelector('.clothes__item-favorite');
favorite.addEventListener('click', function() {
favorite.classList.toggle("favorite--active");
});
body {
background-color: #000;
}
.clothes__item-favorite {
display: block;
position: absolute;
background-color: #fff;
width: 2.3rem;
height: 2.3rem;
border-radius: 100%;
left: 1.25rem;
top: 1.25rem;
font-size: 0;
transition: 0.3s;
cursor: pointer;
}
.clothes__item-favorite:hover {
background-color: #fc7a7a;
}
.favorite--active {
background-color: #fc7a7a;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<i class="clothes__item-favorite">Добавить в избранное</i>
</body>
</html>

尝试这样做:

const favorite = document.querySelectorAll('.clothes__item-favorite');
for (element of favorite) {
element.addEventListener('click', function() {
element.classList.toggle("favorite--active");
});
}

document.querySelectorAll返回与选择器匹配的所有元素的可迭代项。您必须对每一个元素进行迭代。

最新更新