<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(指令中做到这一点。那么,请问我该怎么做?我会感谢你的努力。
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);
});
});
我将余额和消息移出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