I'm not sure if it's possible, but I'd like to use one unique function to trigger 4 different buttons to count a value (+ and -). But there are four different span values, for example, if I trigger forest it will only add or remove from forest, if I do it for town it will only trigger for town, and so on.
// set inital value to zero let count = 0; // select value and buttons const valueForest = document.querySelector("#valueForest"); const btns = document.querySelectorAll(".btn"); btns.forEach(function (btn) { btn.addEventListener("click", function (e) { const styles = e.currentTarget.classList; if (styles.contains("decrease")) { count--; } else if (styles.contains("increase")) { count++; } else { count = 0; } if (count > 0) { valueForest.style.color = "green"; } if (count < 0) { valueForest.style.color = "red"; } if (count === 0) { valueForest.style.color = "#222"; } valueForest.textContent = count; }); });
<div class="scoreDiv"> <h3>Input below the quantity of each tile in the end of the game:</h3> <div class="scoreItem"> <h4>Forest</h4> <button class="btn decrease">-</button> <span class="value" id="valueForest">0</span> <button class="btn increase">+</button> <h4>SOMA</h4> </div> <div class="scoreItem"> <h4>Town</h4> <button class="btn decrease">-</button> <span class="value" id="valueTown">0</span> <button class="btn increase">+</button> <h4>SOMA</h4> </div> <div class="scoreItem"> <h4>Production</h4> <button class="btn decrease">-</button> <span class="value" id="valueProduction">0</span> <button class="btn increase">+</button> <h4>SOMA</h4> </div> <div class="scoreItem"> <h4>Factory</h4> <button class="btn decrease">-</button> <span class="value" id="valueFactory">0</span> <button class="btn increase">+</button> <h4>SOMA</h4> </div> </div>
from Recent Questions - Stack Overflow https://stackoverflow.com/questions/65375594/same-function-for-different-buttons-javascript Lucas Marodin de paiva
没有评论:
发表评论