jQuery实现金额录入框
前端开发过程中,通常会用到数值录入框,比如要求输入金额,禁止录入非数值字符,也禁止粘贴非数值字符,怎么实现呢?
首先通过(function($){ })(jQuery);即时执行函数用于模块隔离,可以避免与其他功能模块、插件之间产生变量污染问题,所有私有的全局变量可以放在即时执行函数的头部。
然后在jquery原型上扩展numbox方法,直接上代码
(function($){
//数值输入框
$.fn.numbox=function(options){
vartype=(typeofoptions);
if(type=='object'){
//创建numbox对象
if(options.width)this.width(options.width);
if(options.height)this.height(options.height);
this.bind("inputpropertychange",function(obj){
numbox_propertychange(obj.target);
});
this.bind("change",function(obj){
varonChange=options.onChange;
if(!onChange)return;
varnumValue=Number(obj.target.value);
onChange(numValue);
});
this.bind("hide",function(obj){
varonHide=options.onHide;
if(!onHide)return;
varnumValue=Number(obj.target.value);
onHide(numValue);
});
returnthis;
}
elseif(type=='string'){
//type为字符串类型,代表调用numbox对象中的方法
varmethod=eval(options);
if(method)returnmethod(this,arguments);
}
}
//属性值变化事件
functionnumbox_propertychange(numbox){
if(numbox.value=='-'||numbox.value==numbox.oldvalue)return;
varnumvalue=Number(numbox.value);
if(isNaN(numvalue)){
numbox.value=numbox.oldvalue;
}
else{
numbox.oldvalue=numbox.value;
}
}
//获取值
functiongetValue(numbox){
varvalue=numbox.val();
returnNumber(value);
}
//设置值
functionsetValue(numbox,params){
if(params[1]==undefined)return;
varnumvalue=Number(params[1]);
if(!isNaN(numvalue)){
for(vari=0;i<numbox.length;i++){
numbox[i].focus();
numbox[i].value=numvalue;
numbox[i].oldvalue=numvalue;
}
}
}
})(jQuery);//这里传入jQuery对象作为参数,是为了避免在模块内部直接去访问全局对象,避免过度依赖其他模块,降低耦合度,更加规范化,可控性更高,可参考其他成熟jQuery插件(easyui、bootstrap)
调用方法如下
<body>
<inputid="test"/>
<script>
$("#test").numbox({
width:150,
height:20
});
</script>
</body>
以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,同时也希望多多支持毛票票!