問題描述
我是 javascript 新手,我正在嘗試學習 JS 中的函數等,并嘗試添加 2 個數字
I'm new to javascript , I'm trying learning how functions etc in JS and trying to add 2 numbers
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>JS ADD</title>
</head>
<body>
<h1>Funcitons is JS</h1>
<input type="number" id="num1">
<input type="number" id="num2">
<button type="button" onclick="addNumAction()">
Add
</button>
<script>
function addNum(n1, n2) {
return parseInt(n1) + parseInt(n2);
}
function addNumAction() {
var n1 = document.getElementById("num1").value;
var n2 = document.getElementById("num2").value;
var sum = addNum(n1, n2);
window.alert("" + sum);
}
</script>
</body>
</html>
如果我刪除 parseInt() 值僅被視為字符串,那么使用 <input type="number">
有什么意義?請向我解釋.使用什么字段來獲取數字輸入?
If I remove the parseInt() the value is treated as a string only , then what is the point of using <input type="number">
?please explain to me.
what field to use for getting input as a number?
推薦答案
得到一個字符串是正常的.
It's normal you get a string.
數字類型的目的是移動瀏覽器使用它來顯示正確的鍵盤,一些瀏覽器使用它來進行驗證.例如,email
類型將顯示帶有 @ 和 '.' 的鍵盤.在鍵盤上,number
將顯示一個數字鍵盤.
The purpose of the number type is that mobile browsers use this for showing the right keyboards and some browsers use this for validation purposes. For example the email
type will show a keyboard with the @ and '.' on the keyboard and number
will show a numeric keyboard.
這篇關于HTML 輸入類型=“數字";從 javascript 訪問時仍然返回一個字符串的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!