javascript - 余额为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) 指令中执行此操作。那么,请问我该怎么做?我会感谢你的努力。
解决方案
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
推荐阅读
- multithreading - 用一个配方进行多线程构建?
- c# - C# WPF - 带有 DataTemplate 的 ListBox - 添加额外的“标题”行
- sql - VB6 的 SQL Server 和 ADO 数据类型 - 为存储过程中的 VARCHAR(MAX) OUTPUT 参数设置什么大小?
- list - elisp 如何将 lambda 应用于列表?
- javascript - Javascript 切换多个列类
- .net - 在 VB.Net 中铸造奇怪的东西
- c# - 为什么我的checkedListBox 在C# 中抛出NullReferenceException?
- ag-grid - ag-grid:需要将多个字段聚合到一个单元格内的表格中
- r - 在 R 中添加时间
- python - 当前事务发生错误。在“原子”块结束之前,您无法执行查询