我在尝试使用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>
对于这个例子,我希望能够实现三件事。
我尝试使用以下代码执行此操作,但我没有在哪里,或者遗漏了什么?
$('.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
。thepercentage as
值then used an
if if语句,如果我需要加或减符号,如果它低于0.00%或者过度。
请找到我尝试的JSFiddle:JSFiddle here
答案 0 :(得分:1)
您的JavaScript中有几个问题。以下是我可以看到的两个主要问题:
以下是工作代码:
$(document).ready(function (){
$('.thepercentage').keyup(function(e){
thenum = $('.thenumber').val();
thepercentage = $('.thepercentage').val();
setTimeout(function() {
if(parseInt(thepercentage) > 0.01) {
var thepercentagenum = parseFloat($(".thepercentage").val());
var numberhere = parseFloat($(".thenumber").val());
console.log(thepercentagenum + "and" + numberhere);
var thereplacement = (numberhere * thepercentagenum/100.0); // percent means divide by 100
$('.number-forecast').text(thereplacement);
} else {
var thepercentagenums = $(".thepercentage").val();
var numberheres = parseInt($(".thenumber").val());
var thereplacements = -(numberheres * thepercentagenums/100); // percent means divide by 100
$('.number-forecast').text(thereplacements);
}
}, 500);
});
});
Here是正确工作的小提琴。祝你好运!