完成一个加法功能使用到类型转换功能

需求:两个输入框,点击等号按钮,读取输入的值,字符串转数字后相加,把结果输出到结果框。

重点:.val()拿到的值是字符串类型,直接 one+two 会变成字符串拼接,不是数学加法;要用parseInt()转为整数。

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm26.aspx.cs" Inherits="WebApplication1.WebForm26" %>
<html xmlns="[http://www.w3.org/1999/xhtml](http://www.w3.org/1999/xhtml)">
<head runat="server">
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title></title>
    <script src="[http://libs.baidu.com/jquery/1.8.3/jquery.min.js](http://libs.baidu.com/jquery/1.8.3/jquery.min.js)"></script>
    <script type="text/javascript">
        function dealAdd() {
            var one = $('#one').val();
            var two = $('#two').val();
            // 不加parseInt会是字符串拼接,例如"1"+"2"得到"12"
            $('#result').val(parseInt(one) + parseInt(two));
        }
    </script>
</head>
<body>
    <input type="text" id="one" />
    <label>+</label>
    <input type="text" id="two" />
    <input type="button" value="=" onclick="dealAdd()" />
    <input type="text" id="result" />
</body>
</html>
Code language: HTML, XML (xml)

说明:

  1. $('#one').val() 获取输入框内容,类型为字符串
  2. parseInt():把字符串转成整数;如果要支持小数可以换成parseFloat()
  3. 转换后执行数学加法,赋值给结果输入框

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注