<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <style type="text/css"> div { display: inline-block; margin-left: 37%; } button { margin-top: 10px; } span { color: #999; font: 12px/3.5 Tahoma; } </style> <script src="http://apps.bdimg.com/libs/jquery/2.1.4/jquery.js"></script> </head> <body> <div> <input type="text" value="1,2,3,4,5,6,7,8,9,10,11,12,13,14,15"> <span>数字之间用半角逗号 “,” 隔开</span><br/> <button>求和</button> <p></p> </div> <script> $("input").keyup(function(e){ this.value = this.value.replace(/[^(\d)|(,)]/,""); }); $("button").on("click", function(){ var sum = 0; var op = $("input").val().split(","); for (var i = 0; i < op.length; i++) { sum = sum + parseInt(op[i]); } $("p").text(sum); }) </script> </body> </html>
时间: 2024-10-07 08:48:10