余额为0时如何创建余额不足消息?

时间:2020-07-29 01:26:39

标签: javascript html jquery

<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)指令中执行此操作。 所以,请问我该怎么做?感谢您的努力。

2 个答案:

答案 0 :(得分:1)

我将天平和消息移出if/else,以便在x === 0时显示一条消息。这是您要寻找的吗?

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);
  });
});

注意:如果您还没有看到<condition? ? <true> : <false>,请参见https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Conditional_Operator

答案 1 :(得分:1)

Please try to this code i hope helpfull thanks.

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 (true) {
        x += sum;
        $("#balance").text(x.toFixed(2));
         $("#message").text(x === 0 ? "Balance insufficient!" : '');
      } 
      else {
        x -= sum;
        $("#balance").text(x.toFixed(2));
        $("#message").text(x === 0 ? "Balance insufficient!" : '');
      }

    },500);
  });
});