HTML输入类型=“数字”从javascript访问时仍然返回一个字符串 [英] HTML input type="number" still returning a string when accessed from javascript

查看:160
本文介绍了HTML输入类型=“数字”从javascript访问时仍然返回一个字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是新来的JavaScript,我试图学习如何在JS等功能,并试图添加2个数字



< ;!

如果我删除了parseInt(),那么该值只会被视为一个字符串,那么使用< input type =number> 的意义何在?请向我解释。
用于输入数字的字段是什么?

解决方案

正常情况下,您得到一个字符串。



数字类型的目的在于移动浏览器使用它来显示正确的键盘,并且一些浏览器将其用于验证目的。例如,电子邮件类型将在键盘上显示带有@和'。'的键盘,并且 number 将显示一个数字键盘。


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>

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.

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访问时仍然返回一个字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆