
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>数组求和与字符串求和</title>
<style type="text/css">
#case {
width: 40%;
height: 100px;
margin: 50px auto;
}
input {
width: 60%;
height: 30px
}
p:last-child {
background: #00FFFF;
width: 50%;
height: 50px;
text-align: center;
line-height: 50px;
margin: 20px auto;
cursor: pointer;
}
</style>
<script type="text/javascript">
window.onload = function() {
var oInput = document.getElementsByTagName("input")[0];
var oBtn = document.getElementsByTagName("p")[0];
oInput.onkeyup=function(){
this.value=this.value.replace(/[^(\d)|(,)]/,"")
}
oBtn.onclick = function() {
var arr = oInput.value.split(",");
var sum = 0;
for (var item, i = 0; item = arr[i++];) {
sum += parseInt(item);
}
alert(sum)
}
}
</script>
</head>
<body>
<div id="case">
<form>
<input type="text" value="1,2,3,4" id="demo" />(以逗号隔开)
</form>
<p>点击求和</p>
</div>
</body>
</html>