HTML input type=quot;numberquot; still returning a string when accessed from javascript(HTML 输入类型=“数字;从 javascript 访问时仍然返回一个字符串)
问题描述
我是 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 访问时仍然返回一个字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:HTML 输入类型=“数字";从 javascript 访问时仍然返回一个字符串


基础教程推荐
- 原生拖动事件后如何获取 mouseup 事件? 2022-01-01
- npm start 错误与 create-react-app 2022-01-01
- Bootstrap 模态出现在背景下 2022-01-01
- Bokeh Div文本对齐 2022-01-01
- 即使用户允许,Gmail 也会隐藏外部电子邮件图片 2022-01-01
- 检查 HTML5 拖放文件类型 2022-01-01
- 在 contenteditable 中精确拖放 2022-01-01
- fetch 是否支持原生多文件上传? 2022-01-01
- Fabric JS绘制具有活动形状的多边形 2022-01-01
- 如何添加到目前为止的天数? 2022-01-01