增加和减少Javascript中的值

时间:2018-11-30 19:30:56

标签: javascript ecmascript-6

我相信我的问题可能有一个简单的解决方案,但我不知道该如何解决...

Codepen

let x;
let op;
let horamin = 10;
let horamax = 15;

function hora (x, op){
    if (x > horamin && x < horamax) {
        if (op == 'soma') {
            document.querySelector(".hora").innerText = x + 1
        } else {
            document.querySelector(".hora").innerText = x - 1
        } ;
    }
}


document.querySelector(".horaU").addEventListener('click', (event) = > {
        x = parseInt(document.querySelector(".hora").innerText);
        op = "soma";
        hora(x, op);
        //document.querySelector(".hora").innerText = x+1;
});

document.querySelector(".horaD").addEventListener('click', (event) = > {
        x = parseInt(document.querySelector(".hora").innerText);
        op = "diminui";
        hora(x, op)
});

一切正常, 直到 ,我达到了horaminhoramax的价值。然后,无论我单击多少,它都将停止工作。我该如何解决?

1 个答案:

答案 0 :(得分:4)

如果数字超出范围,您只是阻止增加和减少,我想您想始终允许以下操作之一:

  if (op == 'soma') {
    if(x >= horamax) return;
    document.querySelector(".hora").innerText = x +1
  } else {
    if(x <= horamin) return;
    document.querySelector(".hora").innerText = x -1
  }