使用 Javascript 按钮增加数字

Increase number with Javascript button

我在 javascript 搜索制作一个简单的计数器。

他有一个增加数字的按钮,另一个减少数字的按钮。

就像是一个有限的计数器,他们可以增加超过 4/4。

let addSkill = document.querySelector('#addSkill');
let subSkill = document.querySelector('#subSkill');
let counter = document.querySelector('#counter');

addSkill.addEventListener('click', () => {
  if (counter.value = 4) {
    counter.value = 4;
  } else {
    counter.value = parseInt(counter.value) + 1;
  }
});

subSkill.addEventListener('click', () => {
  if (counter.value <= 0) {
    counter.value = 0;
  } else {
    counter.value = parseInt(counter.value) - 1;
  }
});
<span class="badge badge-pill badge-info">
  <span id="counter">0</span>
  <span>/4</span>
</span>

<div class="modal-footer border-top-0">
  <button type="radio" class="btn btn-warning" id="subSkill" data-dismiss="modal">Later</button>
  <button type="radio" class="btn btn-primary" id="addSkill" data-dismiss="modal">Now</button>
</div>

A <span> 没有 value,您需要阅读并设置它的文本。 = 也不是比较运算符。

您可以将其简化为:

let addSkill = document.querySelector('#addSkill');
let subSkill = document.querySelector('#subSkill');
let counter = document.querySelector('#counter');

addSkill.addEventListener('click', () => {
  let count = parseInt(counter.textContent)
  if (count < 4) {
    counter.textContent = ++count;
  }
});

subSkill.addEventListener('click', () => {
  let count = parseInt(counter.textContent)
  if (count > 0) {
    counter.textContent = --count;
  }
});
<span class="badge badge-pill badge-info"><span id="counter">0</span><span>/4</span></span>

<button type="radio" class="btn btn-warning" id="subSkill" data-dismiss="modal">Later</button>
<button type="radio" class="btn btn-primary" id="addSkill" data-dismiss="modal">Now</button>