数字每隔四位用空格分隔代码实例

快乐打工仔 分类:实例代码

分享一段代码实例,它实现了数字每隔四位就用空格分隔。

这样的效果在填写银行卡的时候十分常见,这也是非常人性化的举措。

代码实例如下:

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="author" content="http://www.pipipi.net/" />
<title>前端教程网</title>
<script src="http://libs.baidu.com/jquery/1.9.0/jquery.js"></script>
<script>
$(document).ready(function () {
  $('#ant').on('keyup mouseout input', function () {
    var $this = $(this);
    var v = $this.val();
    /\S{5}/.test(v) && $this.val(v.replace(/\s/g, '').replace(/(.{4})/g, "$1 "));
  });
})
</script>
</head>
<body>
<input type="text" id="ant" />
</body>
</html>

上面的代码实现了我们的要求,更多内容可以参阅相关阅读。

相关阅读:

(1).on()可以参阅jquery on()一章节。

(2).keyup事件可以参阅jQuery keyup事件一章节。

(3).val()方法可以参阅jQuery val()一章节。

(4).test()方法可以参阅正则表达式test()函数一章节。

(5).replace()可以参阅正则表达式replace()函数一章节。

(6).子表达式可以参阅正则表达式分组一章节。

回复

我来回复
  • 暂无回复内容