效果 :
代码 :
var calculator = function(obj){ this.obj = obj; this.maxValue = obj.maxValue; this.minValue = obj.minValue; this.operationSymbol = obj.operationSymbol; this.increasing = obj.increasing; this.init(); //Initialization function }; calculator.prototype = { constructor : this, init : function(){ var _this = this; if(_this.obj.obj.val() > _this.maxValue || isNaN(_this.obj.obj.val()) != false){ _this.obj.obj.val(_this.maxValue); return; } switch(_this.operationSymbol){ case ‘plus‘: _this.plus(_this.obj, _this.increasing); break; case ‘minus‘: _this.minus(_this.obj, _this.increasing); break; case ‘times‘: _this.times(_this.obj, _this.increasing); break; case ‘divide‘: _this.divide(_this.obj, _this.increasing); break; defaults : break; } }, plus : function(obj,increasing){ var puls_this = this; puls_this.initValue = parseInt(obj.obj.val()); if(puls_this.initValue >= puls_this.minValue && puls_this.initValue != puls_this.maxValue && isNaN(puls_this.initValue)==false){ obj.obj.val(parseInt(puls_this.initValue + puls_this.increasing)); } }, minus : function(obj,increasing){ var minus_this = this; minus_this.initValue = obj.obj.val(); if(minus_this.initValue != minus_this.minValue && isNaN(minus_this.initValue)==false) obj.obj.val(parseInt(minus_this.initValue - minus_this.increasing)); }, times : function(obj,increasing){ var times_this = this; times_this.initValue = obj.obj.val(); if(isNaN(times_this.initValue)==false) obj.obj.val(parseInt(times_this.initValue * times_this.increasing)); }, divide : function(obj,increasing){ var divide_this = this; divide_this.initValue = obj.obj.val(); if(isNaN(divide_this.initValue) == false) obj.obj.val(parseInt(divide_this.initValue / divide_this.increasing)); } }; window.calculator = calculator;
调用:
<a href="javascript:void(0);" onClick="counter(‘defaultValue‘,‘minus‘)">-</a> <input name="" type="text" value="1" id="defaultValue" /> <a href="javascript:void(0);" onClick="counter(‘defaultValue‘,‘plus‘)">+</a></div> <script type="text/javascript"> function counter(obje,symbol){ new calculator({ obj:$(‘#‘+obje), maxValue : 99, minValue : 0, operationSymbol : symbol, increasing : 1 }); } </script>
时间: 2024-10-14 04:26:45