您的位置:首页 > Web前端 > JQuery

jquery练习1 字符串分割求数字和

2017-12-11 11:18 363 查看
这两天开始学习jquery,自己练习一下,记录在博客里

这次的题目是文本框输入一系列数字,用,分隔,进行求和

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>

<head>
<meta http-equiv="Content-Type" content="text/html charset=utf-8" />
<script src="http://code.jquery.com/jquery-1.8.3.js">
</script>
<script type="text/javascript">
$(document).ready(function() {
$("#sumBtn").click(function() {
var $numList = $("#numList").val();
var arrayList=new Array();
arrayList=$numList.split(",");
// var arrayList=new new Array($numList.split(","));//这是错误的写法!
var total=0;
for(var i=0;i<arrayList.length;i++){
total +=parseInt(arrayList[i]);
// total +=arrayList[i];
//错误的写法,例如你输入1,2,3 输出就是0123
//必须要把arrayList[i]视为数值
}
$("#result").text(total);
});
});
</script>
<style type="text/css">
.wrapper {
/*margin: 0 auto;*/
text-align: center;//保证其中的元素居中
}
.wrapper *{
margin-top:20px;
}
</style>
<title>
输入一系列数字 用,分隔,按按钮求和
</title>
</head>

<body>
<div class="wrapper">
<input type="text" id="numList" name="nums" placeholder="请输入数字,用,分隔" />
<br/>
<button type="button" id="sumBtn">求和</button>
<br/>
<p>数字之和为:<span id="result" style="color: red;">0</span></p>
</div>
</body>

</html>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐