简单的计数器将数字的颜色更改为红色(减少)绿色(增加)以某种方式难以使黑色为零

simple counter changes color of digit to red(decrease) green(increase) somehow struggle to have zero black

我刚刚完成了一些简单的 js 项目,但不知何故卡在了这里。 我有一个计数器,它有两个按钮,可以将显示的值增加或减少一个。

负值红色 - 正值绿色

零应该是黑色的

我已经考虑过在范围之外创建另一个变量来跟踪计数,但它也不太奏效。

感谢您的帮助

const counter = document.getElementById('counter');
const buttonDown = document.querySelector('.prevBtn');
const buttonUp = document.querySelector('.nextBtn');



buttonDown.addEventListener('click', function() {
  console.log(counter.textContent == 0);
  console.log('test')
  if (counter.textContent == 0) {
    counter.style.color = 'black';
  }
  counter.textContent--;
  if (counter.textContent < 0 ) {
    counter.style.color = 'red';
  } 
})

buttonUp.addEventListener('click', function() {
  
  if (counter.textContent == 0) {
    counter.style.color = 'orange';
  }
  counter.textContent++;
  if (counter.textContent > 0 )
  counter.style.color = 'green';


})

更改如下

   if (parseInt(counter.textContent) == 0) {

您的代码已更正:

const counter = document.getElementById('counter');
const buttonDown = document.querySelector('.prevBtn');
const buttonUp = document.querySelector('.nextBtn');

buttonDown.addEventListener('click', function() {
  var counterNumericValue = Number(counter.textContent);
  if(counterNumericValue == 0)
    counter.style.color = 'black';
  else {
    counterNumericValue--;
    counter.textContent = counterNumericValue;
    counter.style.color = 'red';
  } 
});

buttonUp.addEventListener('click', function() {
  var counterNumericValue = Number(counter.textContent);
  counterNumericValue++;
  counter.textContent = counterNumericValue;
  counter.style.color = 'green';
});

现在我明白你需要什么了:

const counter = document.getElementById('counter');
const buttonDown = document.querySelector('.prevBtn');
const buttonUp = document.querySelector('.nextBtn');

function updateCounter(change) {
  var counterNumericValue = Number(counter.textContent)+change;
  counter.textContent = counterNumericValue;
  counter.style.color=(counterNumericValue>0)?"green":(counterNumericValue<0):"red":"black";
}

buttonDown.addEventListener('click', function() {
  updateCounter(-1);
});

buttonUp.addEventListener('click', function() {
  updateCounter(1);
});