我很难使用JavaScript将类添加到按钮中。
上下文:我有多个具有帖子和“类似”按钮的Instragram类型格式的卡。我想添加一类 card__ like button ,它将图像更改为填充的心脏,但我记得QuerySelector仅适用于第一个元素,相反,我尝试使用QuerySelectorall对任何东西。
第一个attemp:
// Controls for active like button
let likeButton = document.querySelector(".card__like-button");
// Event listener for like button click
likeButton.addEventListener("click", likeButtonClick);
// Add class on button click
function likeButtonClick() {
likeButton.classList.toggle("card__like-button_active");
}
第二个attemp
// Controls for active like button
let likeButton = document.querySelectorAll(".card__like-button");
// Event listener for like button click
likeButton.addEventListener("click", likeButtonClick);
// Add class on button click
function likeButtonClick() {
likeButton.classList.toggle("card__like-button_active");
}
我创建了以下 codepen 问题。
我已经在网站上搜索了W3Schools文档等,似乎找不到我在做什么错。
I'm having difficulty with using Javascript to add a class to a button.
Context: I have multiple cards in an instragram type format with a post and a "like" button. I want to add a class of card__like-button which changes the image to a filled heart but i remembered that querySelector only applies to the first element, instead i tried using querySelectorAll but now the code doesn't apply to anything.
First attemp:
// Controls for active like button
let likeButton = document.querySelector(".card__like-button");
// Event listener for like button click
likeButton.addEventListener("click", likeButtonClick);
// Add class on button click
function likeButtonClick() {
likeButton.classList.toggle("card__like-button_active");
}
Second attemp
// Controls for active like button
let likeButton = document.querySelectorAll(".card__like-button");
// Event listener for like button click
likeButton.addEventListener("click", likeButtonClick);
// Add class on button click
function likeButtonClick() {
likeButton.classList.toggle("card__like-button_active");
}
I created the following codepen to replicate the problem.
I've search on the site, w3schools documentation, etc. and can't seem to find what am I doing wrong.
发布评论
评论(2)
尝试:
Try it :
因为有文档。querySelectorAll方法将返回一个Nodelist ,您无法将AddeventListener事件直接分配到列表。
相反,您必须循环浏览每个元素并为其分配事件
Because of the document.querySelectorAll method will return an array of NodeList details see here, you cannot directly assign the addEventListener event to a list.
Instead, you have to loop through each element and assign events to it