练习地址:http://www.fgm.cc/learn/lesson2/03.html
主要思路就是读取input的value,然后将这个字符串分割成一个数组,这个时候数组里面装的还是字符串,所以在求和的循环中,用Number()函数将字符串转换为数字。按钮点击事件将结果的innerText变为sum,display为block。
代码如下:
HTML
<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="utf-8">
<title>求出数组中所有数字的和</title>
<link rel="stylesheet" type="text/css" href="3_sum.css">
</head>
<body>
<div id="container">
<input type="text" value="1,2,3,4,5,6,7,8,9,10,11,12,13,14,15">
<p id="line">输入数字求和,数字之间用半角“,”号分隔</p>
<button>求和</button>
<p id="result"></p>
</div>
<script type="text/javascript" src="3_sum.js"></script>
</body>
</html>
css
#container {
width: 520px;
margin: 0 auto;
text-align: right;
font-size: 12px;
}
input {
width: 250px;
/*如果下面设置了float那文本框不可编辑*/
/*float: left;*/
}
#line {
opacity: 0.5;
display: block;
float: right;
text-indent: 10px;
line-height: 5px;
}
#result {
font-size: 30px;
font-weight: bold;
color: red;
position: relative;
left: -440px;
}
button {
position: relative;
left: -210px;
top: 20px;
}
javascript
window.onload = function() {
var btn = document.getElementsByTagName("button")[0];
btn.onclick = function() {
var str = document.getElementsByTagName("input")[0].value;
var result = document.getElementById("result");
var num = str.split(",");
var sum = 0;
var number;
for(var i=0; i<num.length; i++){
number = Number(num[i]);
sum += number;
}
result.innerText = sum;
result.style.display = block;
}
}