//知识点一:
将字符串折分成数组
input.value.split(",");
//知识点二:
阻止用户输入非法字符
通过正则表达式,不是数字与单引号过去除
this.value = this.value.replace(/[^(d)|(,)]/,"");
1 <!DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 2 <html xmlns="http://www.w3.org/1999/xhtml"><head> 3 <meta http-equiv="Content-Type" content="text/html; charset=gbk"> 4 <title>求出数组中所有数字的和</title> 5 <style type="text/css"> 6 body{color:#999;font:12px/1.5 Tahoma;} 7 #outer{width:500px;margin:0 auto;} 8 #outer input{padding:3px;border:1px solid #ccc;font-family:inherit;width:220px;margin-right:10px;} 9 .sum{font-size:30px;color:red;} 10 </style> 11 </head> 12 <body> 13 <div id="outer"> 14 <label> 15 <input value="1,2,3,4,5,6,7" type="text"> 16 <span>输入数字求和,数字之间用半角","号分隔</span> 17 </label> 18 <p><button>求和</button></p> 19 <strong class="sum">120</strong> 20 </div> 21 <script type="text/javascript"> 22 //知识点一: 23 24 //input.value.split(","); 25 26 //知识点二: 27 //阻止用户输入非法字符 28 //通过正则表达式,不是数字与单引号过去除 29 // this.value = this.value.replace(/[^(d)|(,)]/,""); 30 31 32 33 var button = document.getElementsByTagName("button")[0]; 34 var input = document.getElementsByTagName("input")[0]; 35 var strong = document.getElementsByTagName("strong")[0]; 36 37 //限制用户只能输入数字和,号 38 input.onkeyup = function(){ 39 this.value = this.value.replace(/[^(d)|(,)]/,""); 40 41 } 42 43 button.onclick = function(){ 44 //将字符串折分成数组 45 var tmp = input.value.split(","); 46 var sum = 0; 47 for(var i=0;i<tmp.length;i++){ 48 sum += parseInt(tmp[i]); 49 } 50 strong.innerHTML = sum; 51 }; 52 53 </script> 54 </body> 55 </html>