需求:两个输入框,点击等号按钮,读取输入的值,字符串转数字后相加,把结果输出到结果框。
重点:
.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)
说明:
$('#one').val()获取输入框内容,类型为字符串parseInt():把字符串转成整数;如果要支持小数可以换成parseFloat()- 转换后执行数学加法,赋值给结果输入框
Previous: 做一个练习-完成左右选择框-权限清单选择功能
Next: 练习一下-完成倒计时功能