欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

jQuery实现金额录入框

程序员文章站 2023-02-15 19:51:27
前端开发过程中,通常会用到数值录入框,比如要求输入金额,禁止录入非数值字符,也禁止粘贴非数值字符,怎么实现呢? 首先通过(function($){  })(jq...

前端开发过程中,通常会用到数值录入框,比如要求输入金额,禁止录入非数值字符,也禁止粘贴非数值字符,怎么实现呢?

首先通过(function($){  })(jquery); 即时执行函数用于模块隔离,可以避免与其他功能模块、插件之间产生变量污染问题,所有私有的全局变量可以放在即时执行函数的头部。

然后在jquery原型上扩展numbox方法,直接上代码

(function ($) {
 // 数值输入框
 $.fn.numbox = function (options) {
 var type = (typeof options);
 if (type == 'object') {
       // 创建numbox对象
  if (options.width) this.width(options.width);
  if (options.height) this.height(options.height);
  this.bind("input propertychange", function (obj) {
  numbox_propertychange(obj.target);
  });
  this.bind("change", function (obj) {
  var onchange = options.onchange;
  if (!onchange) return;
  var numvalue = number(obj.target.value);
  onchange(numvalue);
  });
  this.bind("hide", function (obj) {
  var onhide = options.onhide;
  if (!onhide) return;
  var numvalue = number(obj.target.value);
  onhide(numvalue);
  });
  return this;
 }
 else if (type == 'string') {
       // type为字符串类型,代表调用numbox对象中的方法
  var method = eval(options);
  if (method) return method(this, arguments);
 }
 }
 // 属性值变化事件
 function numbox_propertychange(numbox) {
 if (numbox.value == '-' || numbox.value == numbox.oldvalue) return;
 var numvalue = number(numbox.value);
 if (isnan(numvalue)) {
  numbox.value = numbox.oldvalue;
 }
 else {
  numbox.oldvalue = numbox.value;
 }
 }
 // 获取值
 function getvalue(numbox) {
 var value = numbox.val();
 return number(value);
 }
 // 设置值
 function setvalue(numbox, params) {
 if (params[1] == undefined) return;
 var numvalue = number(params[1]);
 if (!isnan(numvalue)) {
  for (var i = 0; i < numbox.length; i++) {
  numbox[i].focus();
  numbox[i].value = numvalue;
  numbox[i].oldvalue = numvalue;
  }
 }
 }
})(jquery); // 这里传入jquery对象作为参数,是为了避免在模块内部直接去访问全局对象,避免过度依赖其他模块,降低耦合度,更加规范化,可控性更高,可参考其他成熟jquery插件(easyui、bootstrap)

调用方法如下

<body>
 <input id="test" />
 <script>
 $("#test").numbox({
  width: 150,
  height: 20
 });
 </script>
</body>

以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,同时也希望多多支持!