我希望得到用户的输入,例如乘以1.3并立即输出到窗口,就像用户类型函数正在执行并立即在HTML中显示一样。它是怎么做到的?
在这里我的代码
function calc() {
amount = document.getElementById("amount").value;
num2 = 1.3;
document.getElementById("result").innerHTML = amount * num2;
return result;
}
<input id='amount', type="text" >
<button onclick="calc()"> Buy Now! </button>
<p> Result is: <br>
<span id = "result"> </span>
<input type="text"onkeyup="calc()">
首先,我建议更正您的HTML:
这个逗号怎么样?属性不需要任何分隔符。
<input id='amount', type="text" >
只是放一个空格:
<input id='amount' type="text" >
我还删除了无用的空格,这里是一个干净的HTML:
<input id='amount' type="text">
<button onclick="calc()">Buy Now!</button>
<p>Result is:<br>
<span id="result"></span>
然后,让我们开始查看您的选项,并排除那些不适合<input>
文本更改事件的选项:
keydown
事件将无法工作,因为在value
变化之前调用。keypress
事件不会因为相同而有效。keyup
事件,也建议@Dmitri Usanov,将会工作,但是当密钥发布时它被调用,因此并不完美。input
事件将起作用,它是目前最好的解决方案,但它只适用于HTML5。那么,让我们构建代码(你可以看到这个fiddle):
function calc() {
//Here I make the text a Number to then calculate it.
let amount = Number(document.getElementById("amount").value);
let num2 = 1.3;
//Here I declare a precision to avoid strange errors such as 3.900000009
let precision = 2;
//Here I run the calculation and I apply that precision to the result.
let multiplier = Math.pow(10, precision);
let result = Math.round(amount * num2 * multiplier) / multiplier;
//Finally I set the text to the span.
document.getElementById("result").innerHTML = result;
return result;
}
window.addEventListener("load", function() {
document.getElementById("amount").addEventListener("input", function() {
calc(this.value);
});
});
试试这个
function calc(isEsc) {
const num2 = 1.3;
let result = document.getElementById("result"),
amount = document.getElementById("amount");
if (isEsc) {
result.innerHTML = 0;
amount.value = '';
} else {
result.innerHTML = amount.value * num2;
}
}
document.onkeyup = function(evt) {
evt = evt || window.event;
var isEscape = false;
if ("key" in evt) {
isEscape = (evt.key == "Escape" || evt.key == "Esc");
} else {
isEscape = (evt.keyCode == 27);
}
calc(isEscape);
};
<input type="text" id="amount" />
<span id="result">0</span>