js填写银行卡号,每隔4位数字加一个空格

1、原生js写法

1 !function () {
2     document.getElementById('bankCard').onkeyup = function (event) {
3         var v = this.value;
4         if(/\S{5}/.test(v)){
5             this.value = v.replace(/\s/g, '').replace(/(.{4})/g, "$1 ");
6         }
7     };
8 }();

2、jQuery写法

 1 <!DOCTYPE html>
 2 <html lang="en">
 3 <head>
 4     <meta charset="UTF-8">
 5     <title></title>
 6 </head>
 7 <body>
 8 <input type="text" id="J_BankCard"/>
 9 <script src="http://static.ydcss.com/libs/jquery/1.11.2/jquery.js"></script>
10 <script>
11     !function () {
12         $('#J_BankCard').on('keyup mouseout input',function(){
13             var $this = $(this),
14                 v = $this.val();
15             /\S{5}/.test(v) && $this.val(v.replace(/\s/g,'').replace(/(.{4})/g, "$1 "));
16         });
17     }();
18 </script>
19 </body>
20 </html>

 

posted @ 2016-12-16 23:30  以茜为贵  阅读(360)  评论(0编辑  收藏  举报