需要帮助将最大值和最小值添加到计数器

我正在尝试制作一个从0开始并在12结束的计数器,我现在拥有的是一个我无法封顶的计数器。所以基本上,我在设置最大值和最小值时遇到了麻烦。这是我的代码:


<div class="counter8">

  <label id="blank"></label>

  <div class="operations">

    <a href="javascript:void(0)" onclick="dec_num8()" class="dec opr8">⇦</a>

    <span class="count8">0</span>

    <a href="javascript:void(0)" onclick="inc_num8()" class="inc opr8">⇨</a>

  </div>

</div>


<script>

var add=document.querySelector(".inc");

var sub=document.querySelector(".dec");

let counter8=document.querySelector(".count8");




function inc_num8(){

  var temp8=parseInt(counter8.innerText) >> 0;

  counter8.innerText=temp8+1;

  if (temp8 > 12) {

    counter8.value = 12;

  } else {

    counter8.value = temp8;

  }

}

function dec_num8(){

  var temp8=parseInt(counter8.innerText) >> 0;

  counter8.innerText=temp8-1;

}

</script>

增加按钮是我尝试完成这项工作的尝试之一,但失败了。


MMTTMM
浏览 82回答 2
2回答

蝴蝶不菲

您可以使用“数学.max”和“数学”来限制这些值。<div class="counter8">&nbsp; <label id="blank"></label>&nbsp; <div class="operations">&nbsp; &nbsp; <a href="javascript:void(0)" onclick="dec_num8()" class="dec opr8">⇦</a>&nbsp; &nbsp; <span class="count8">0</span>&nbsp; &nbsp; <a href="javascript:void(0)" onclick="inc_num8()" class="inc opr8">⇨</a>&nbsp; </div></div><script>var add=document.querySelector(".inc");var sub=document.querySelector(".dec");let counter8=document.querySelector(".count8");function inc_num8(){&nbsp; var temp8=parseInt(counter8.innerText) >> 0;&nbsp; counter8.innerText=Math.min(12,temp8+1);}function dec_num8(){&nbsp; var temp8=parseInt(counter8.innerText) >> 0;&nbsp; counter8.innerText=Math.max(0,temp8-1);}</script>如果你想使用if分支来修复你的代码,你可以这样做:if (temp8 >= 12) {&nbsp; temp8 = 12;} else {&nbsp; temp8++;}counter8.innerText=temp8;或者在一行上:对于最少的一行,只有翻转版本temp8 = temp8 >= 12 ? temp8 : temp8+1

暮色呼如

您并没有真正限制减号按钮上的最小值计数器。而且,只有在检查条件后才能增加它。所以举个例子:function inc_num8(){&nbsp; var temp8=parseInt(counter8.innerText) >> 0;&nbsp; if (temp8 >= 12) { // here changed to >=&nbsp; &nbsp; counter8.innerText = 12; //also use innerText, not value&nbsp; } else {&nbsp; &nbsp; counter8.innerText=temp8+1;&nbsp; }}function dec_num8(){&nbsp; var temp8=parseInt(counter8.innerText) >> 0;&nbsp; if(temp8 <= 0){ //here changed to <=&nbsp; counter8.innerText = 0;&nbsp; }else{&nbsp; counter8.innerText=temp8-1;&nbsp; }}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript