我对javascript很新。构建自定义javascript计算器以设置某些产品的定价。有时会增加费用。此费用是成本的百分比或实际的美元金额。如果是百分比,则会有百分号。在研究之后,提出了以下解决方案,该解决方案仅在输入美元金额时才有效,但如果输入了百分比则没有。有更好的解决方案吗?
<form name="calculator">
<input type="text" name="cost" placeholder="Cost" onkeyup="calculate()">
<input type="text" name="fee" placeholder="fee" onkeyup="calculate()">
<br>
<p>The answer is: </p>
<p id="testAnswer"></p>
</form>
<script type="text/javascript" >
function calculate(){
var a = Number(document.calculator.cost.value);
var b = Number(document.calculator.fee.value);
if(b==""){
var result1= a;
} else {
if (/^\d+(\.\d+)?%$/.test(b)) {
result1 =(1+b)*a;
} else {
var result1 = b+a;
}
}
document.getElementById("testAnswer").innerHTML = result1;
}
</script>
答案 0 :(得分:0)
因为您要将输入转换为数字:
var a = Number(document.calculator.cost.value);
var b = Number(document.calculator.fee.value);
任何符号都会导致转换失败,因此您将无法执行测试。
var num = Number("234.50%");
console.log(num); // Not a Number
&#13;
相反,在进行转换之前,只需测试.indexOf
符号的存在,当测试无法找到匹配项时,会返回-1
。
var a = document.getElementById("num1");
a.addEventListener("input", function(){
console.clear();
// Always trim leading or trailing spaces from user input
var input = a.value.trim();
var unit = null;
if(input.indexOf("%") > -1){
unit = "Percent";
} else if(input.indexOf("$") > -1) {
unit = "Dollar";
}
console.log(unit); // null until % or $ is entered
// Now that you know what the unit is,
// you can convert to a number. Use parseInt()
// or parseFloat() for this
var inputNum = parseInt(input, 10);
console.log(typeof inputNum, inputNum);
});
&#13;
<input type="text" id="num1">
&#13;
说完所有这些之后,我同意评论说更好的办法是不要求用户输入单位,只提供单选按钮:
var a = document.getElementById("num1");
// Set up click event for radio buttons that enables number input
Array.prototype.slice.call(document.querySelectorAll("input[name='unit']")).forEach(function(btn){
btn.addEventListener("click", function(){
a.removeAttribute("disabled");
});
});
a.addEventListener("input", function(){
console.clear();
// Always trim leading or trailing spaces from user input
var input = a.value.trim();
// Just get the value of the selected radio button
var unit = document.querySelector("input[name='unit']:checked").value;
console.log(unit); // null until % or $ is entered
// Now that you know what the unit is,
// you can convert to a number. Use parseInt()
// or parseFloat() for this
var inputNum = parseInt(input, 10);
console.log(typeof inputNum, inputNum);
});
&#13;
<!-- If you expect only digits, you can use a number type -->
<input type="radio" name="unit" value="%">%
<input type="radio" name="unit" value="$">$
<input type="number" id="num1" disabled>
&#13;