【发布时间】:2018-09-01 07:36:56
【问题描述】:
我在尝试使用 jQuery 加减百分比时遇到了困难。也许我只是没有理解它,对此我深表歉意。
已更新。工作解决方案: JsFiddle
HTML
<div class="number-forecast">New number will replace this. </div>
<div id="numbers">
Number: Example: 0.14556416<br/>
<input class="thenumber" type="tel" maxlength="10" pattern="^\d{2}-\d{3}$" onkeypress="return isNumeric(event)" oninput="maxLengthCheck(this)" value="0.14556416" />
</div>
<div id="percentages">
Percentage: From -100% to 9999%<br/>
<input class="thepercentage" type="tel" maxlength="4" pattern="^\d{2}-\d{3}$" onkeypress="return isNumeric(event)" oninput="maxLengthCheck(this)" />
</div>
对于这个例子,我希望能够实现三件事。
- 添加 10% 应该得到 0.160120576
- 加上 998% 应该等于:1.5982944768
- 从中减去百分比。示例:-30%,其结果应为:0.101894912。
我已尝试使用以下代码执行此操作,但没有找到任何地方,或者遗漏了什么?
$('.thepercentage').keyup(function(e){
thenum = $('.thenumber').val();
thepercentage = $('.thepercentage').val();
setTimeout(function() {
if(parseInt(thepercentage) > 0.01) {
var thepercentagenum = $(".thepercentage").val();
var numberhere = parseInt($(".thenumber").val(), thepercentagenum);
var thereplacement = (numberhere * thepercentagenum/100); // percent means divide by 100
$('.number-forecast').text(thereplacement);
} else {
var thepercentagenums = $(".thepercentage").val();
var numberheres = parseInt($(".thenumber").val(), thepercentagenums);
var thereplacements = -(numberheres * thepercentagenums/100); // percent means divide by 100
$('.number-forecast').text(thereplacements);
}
}, 500);
});
});
所以我使用了keyup 函数来检测变化。然后我检索了.thenumber' and.thepercentageasvaluesthen used anif` 语句来确定是否需要添加或减去符号(如果它低于 0.00% 或更高)。
请找到我尝试的 JSFiddle:JSFiddle here
【问题讨论】:
-
这是小学数学。要增加 10%,请乘以
1.1。 -
parseInt()总是返回一个整数,如果你想得到带小数点的数字,你需要使用parseFloat()。 -
jQuery 并没有真正的数学方法。你问的是纯 JavaScript。
-
@Barmar 我不是在问如何乘法,而是在问如何使用输入将其合并到我的代码中。感谢 parseFloat() 提示。
-
这个问题不清楚你的问题到底是什么。 “我在尝试使用 jQuery 加减百分比时遇到了困难。”这听起来像是一道数学题。
标签: javascript jquery math percentage