gpt4 book ai didi

javascript - 简单的减法函数无法正常工作?

转载 作者:行者123 更新时间:2023-11-28 13:32:55 24 4
gpt4 key购买 nike

我试图允许用户输入他们想要分享的积分数量。当他们点击分享时,积分应该从您可用的积分(500 积分)中减去。您应该能够继续分享,直到您输入的金额大于您拥有的积分。由于某些奇怪的原因,我的问题在于您使用的某些数字会破坏它,例如数字 23 或 83。请自己尝试并提供解决此问题的任何反馈。

<强> JSFiddle

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

});

最佳答案

您正在比较字符串。

将代码更改为:

$('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);
}

});

Fiddle

正如@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);
}

});

关于javascript - 简单的减法函数无法正常工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23525713/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com