我试图让用户输入他们想要分享的点数。当他们达到分享时,积分应该从你可用的点数减去(500分)。您应该能够继续分享,直到您输入的金额大于您拥有的金额。由于一些奇怪的原因,我的问题存在于你使用的某些数字打破它,如数字23或83.自己尝试并提供任何反馈来解决这个问题。
HTML
<input type="text" id="points" readonly></input>
<input type="text" id="points-to-share" placeholder="Share Points"></input>
<button>Share</button>
的jQuery
//Set default value of input
var availablePoints = $('#points').val(500);
$(availablePoints);
// Substracts value from remaining points
$('button').click(function() {
var availablePoints = $('#points').val();
var sharingPoints = $('#points-to-share').val();
if (sharingPoints > availablePoints) {
alert('Not enough Points');
}
else {
var pointsLeft = availablePoints - sharingPoints;
$('#points').val(pointsLeft);
}
});
答案 0 :(得分:5)
您正在比较字符串。
将您的代码更改为:
$('button').click(function() {
var availablePoints = $('#points').val();
var sharingPoints = $('#points-to-share').val();
if (Number(sharingPoints) > Number(availablePoints)) {
alert('Not enough Points');
}
else {
var pointsLeft = availablePoints - sharingPoints;
$('#points').val(pointsLeft);
}
});
正如@ p.s.w.g所指出的那样。 ,最好在开头解析你的输入,所以你不必担心其余的功能。
$('button').click(function() {
var availablePoints = Number($('#points').val());
var sharingPoints = Number($('#points-to-share').val());
if (sharingPoints > availablePoints) {
alert('Not enough Points');
}
else {
var pointsLeft = availablePoints - sharingPoints;
$('#points').val(pointsLeft);
}
});