首页 > 解决方案 > 余额为0时如何创建余额不足消息?

问题描述

<div id="balance">0.00</div>
<div id="sum">0.01</div>
<div id="result">000</div>
<div id="message">000</div>
<button>ROLL</button>
var x = 0;
  $(document).ready(function(){
    $("button").click(function () {
    
    var num = setInterval(function () {
    $("#result").text(Math.floor(Math.random() * 100))
    }, 10);

    setTimeout(function () {
    clearInterval(num);
     var sum = parseFloat($("#sum").html());
     var fnal = $("#result").html();
     if (fnal > 50) {
        x += sum;
        $("#balance").text(x.toFixed(2));
        $("#message").text("Balance insufficient!");
      } 
      else {
        x -= sum;
        $("#balance").text(x.toFixed(2));
        $("#message").text("Balance insufficient!");
      }

    },500);
  });
});

我不知道如何在 (if) 和 (else) 指令中执行此操作。那么,请问我该怎么做?我会感谢你的努力。

标签: javascripthtmljquery

解决方案


I moved the balance and message out of the if/else to show a message when x === 0. Is this what youre looking for?

var x = 0;
$(document).ready(function() {
  $("button").click(function() {
    var num = setInterval(function() {
      $("#result").text(Math.floor(Math.random() * 100));
    }, 10);

    setTimeout(function() {
      clearInterval(num);
      var sum = parseFloat($("#sum").html());
      var fnal = parseFloat($("#result").html());
      if (fnal > 50) {
        x += sum;
      } else {
        x -= sum;
      }
      
      // Moved out of if/else, because it was the same
      $("#balance").text(x.toFixed(2));
      // If x === 0, show message, otherwise clear the text
      $("#message").text(x === 0 ? "Balance insufficient!" : '');

    }, 500);
  });
});

Note: if you havent seen the <condition? ? <true> : <false> yet, see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Conditional_Operator


推荐阅读