[英]how to take the value of an input and plus it by any number in javascript and html?
這是我的代碼,我似乎無法找出它返回 NaN 的原因。 我試着在 addnum function 中給它一個特定的數字,但這也沒有用。
<script>
var output = document.getElementById("output");
var input = document.getElementById("input").value;
var int_input = parseInt(input);
function addnum(N) {
int_input = int_input + N;
output.innerHTML = int_input;
}
document.getElementById("addinput").addEventListener("keyup", function (event) {
if (event.keyCode == 13) {
addnum(6);
}
})
</script>
當您的腳本加載時,輸入為空。 稍后,在 function 中,腳本嘗試將 6 添加到 NaN,這將為您提供 NaN。
這應該有效:
<script>
var output = document.getElementById("output");
var input = document.getElementById("input");
function addnum(N) {
var int_input = parseInt(input.value);
int_input = int_input + N;
output.innerHTML = int_input;
}
// Your eventListener function can be placed here
</script>
這適用於控制台
var input = "12";
var int_input = parseInt(input);
function addnum(N) {
int_input = int_input + N;
console.log(int_input);
}
addnum(6);
用輸入做一個 console.log(),看看它有什么價值。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.