JQuery plugin encapsulation series (1)-amount input box, jquery plugin
During front-end development, a value input box is usually used. For example, you must enter the amount, enter non-numeric characters, or paste non-numeric characters. How can this problem be achieved?
First, use (function ($) {}) (jQuery); instant execution functions are used for module isolation to avoid variable contamination with other functional modules and plug-ins, all private global variables can be placed in the header of the immediate execution function.
Then, expand the numbox method on the jquery prototype and directly add the code
(Function ($) {// value input box $. fn. numbox = function (options) {var type = (typeof options); if (type = 'object '){
// Create the numbox object if (options. width) this. width (options. width); if (options. height) this. height (options. height); this. bind ("input propertychange", function (obj) {numbox_propertychange(obj.tar get) ;}); this. bind ("change", function (obj) {var onChange = options. onChange; if (! OnChange) return; var numValue = Number(obj.tar get. value); onChange (numValue) ;}); this. bind ("hide", function (obj) {var onHide = options. onHide; if (! OnHide) return; var numValue = Number(obj.tar get. value); onHide (numValue) ;}); return this ;} else if (type = 'string '){
// Type is a string type, which indicates calling the method var method = eval (options) in the numbox object; 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 ;}} // obtain the value function getValue (numbox) {va R value = numbox. val (); return Number (value) ;}// set the value of 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); // The jQuery object is input as a parameter to avoid direct access to the Global object within the module and excessive dependency on other modules, reduce coupling, more standardization, and higher controllability. For details, refer to other mature jQuery plug-ins (easyui and bootstrap)
The call method is as follows:
<body> <input id="test" /> <script> $("#test").numbox({ width: 150, height: 20 }); </script></body>