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

标签 javascript jquery

我试图允许用户输入他们想要分享的积分数量。当他们点击分享时,积分应该从您可用的积分(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/

相关文章:

javascript - 使用javascript将网页转换为图像

javascript - 为 load() 添加超时

javascript - 获取浏览器宽度和高度,包括工具栏和菜单大小

javascript - 在 select2 的选项中搜索多个单词

javascript - bootstrap 4.1.3 dropdown+proper+可滚动菜单=闪烁

javascript - 对象属性名称作为变量

javascript - asp.net mvc 通过 javascript 读取 ViewBag 通用列表

javascript - HTML/CSS/Javascript 可滚动的 div 不会滚动?

javascript - C 函数到 JavaScript

javascript - 有人可以帮忙解释一下这段 jQuery 代码吗?