[英]change listener on 2nd click
I have a javascript code where I store an element in an array upon clicking on a button, and change the button from "+" to "-".我有一个 javascript 代码,我在单击按钮时将元素存储在数组中,并将按钮从“+”更改为“-”。 Upon clicking the button again, I want to remove that element from the array.
再次单击按钮后,我想从数组中删除该元素。
I have this code.我有这个代码。 It does the first part well, but it also removes the element without clicking on the button the second time.
它很好地完成了第一部分,但它也删除了元素而没有第二次单击按钮。
let favorites = []
let buttonList = document.querySelectorAll("button")
let click = 0
buttonList.forEach((button, index) => {
button.addEventListener('click', function saveFavourites() {
click++
favorites.push(products[index])
button.textContent = "-"
console.log(favorites)
if (click === 1) {
this.removeEventListener('click', saveFavourites)
}
})
button.addEventListener('click', function removeFavourites() {
click ++
let i = favorites.indexOf(products[index])
favorites.splice(i, 1)
button.textContent = "+"
console.log(favorites)
if (click === 2) {
this.removeEventListener('click', removeFavourites)
}
})
})
You're adding two separate event listeners to the same button element.您正在向同一个按钮元素添加两个单独的事件侦听器。 Use a single event listener and toggle a boolean
flag
variable to keep track of whether the element should be added or removed.使用单个事件侦听器并切换 boolean
flag
变量以跟踪是否应添加或删除元素。
let favorites = []
let buttonList = document.querySelectorAll("button")
buttonList.forEach((button, index) => {
let isAdded = false; // flag variable to track whether the element is added or removed
button.addEventListener('click', function toggleFavourites() {
if (isAdded) {
let i = favorites.indexOf(products[index])
favorites.splice(i, 1)
button.textContent = "+"
isAdded = false;
} else {
favorites.push(products[index])
button.textContent = "-"
isAdded = true;
}
console.log(favorites)
})
})
When the button is clicked, the code checks the value of isAdded
and either adds the element to the favorites
array or removes it.单击该按钮时,代码会检查
isAdded
的值并将该元素添加到favorites
数组或将其删除。
Here is the Demo:- Codesandbox这是演示:- Codesandbox
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.