jQuery實現(xiàn)金額錄入框
前端開發(fā)過程中,通常會用到數(shù)值錄入框,比如要求輸入金額,禁止錄入非數(shù)值字符,也禁止粘貼非數(shù)值字符,怎么實現(xiàn)呢?
首先通過(function($){ })(jQuery); 即時執(zhí)行函數(shù)用于模塊隔離,可以避免與其他功能模塊、插件之間產(chǎn)生變量污染問題,所有私有的全局變量可以放在即時執(zhí)行函數(shù)的頭部。
然后在jquery原型上擴展numbox方法,直接上代碼
(function ($) { // 數(shù)值輸入框 $.fn.numbox = function (options) { var type = (typeof options); if (type == 'object') { // 創(chuàng)建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為字符串類型,代表調(diào)用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); } // 設(shè)置值 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對象作為參數(shù),是為了避免在模塊內(nèi)部直接去訪問全局對象,避免過度依賴其他模塊,降低耦合度,更加規(guī)范化,可控性更高,可參考其他成熟jQuery插件(easyui、bootstrap)
調(diào)用方法如下
<body> <input id="test" /> <script> $("#test").numbox({ width: 150, height: 20 }); </script> </body>
以上就是本文的全部內(nèi)容,希望本文的內(nèi)容對大家的學習或者工作能帶來一定的幫助,同時也希望多多支持腳本之家!
相關(guān)文章
Windows Server 2012 R2 Standard搭建ASP.NET Core環(huán)境圖文教程
這篇文章主要介紹了Windows Server 2012 R2 Standard搭建ASP.NET Core環(huán)境圖文教程,需要的朋友可以參考下2016-07-07解決Asp.net Mvc返回JsonResult中DateTime類型數(shù)據(jù)格式問題的方法
這篇文章主要介紹了解決Asp.net Mvc返回JsonResult中DateTime類型數(shù)據(jù)格式問題的方法,需要的朋友可以參考下2016-06-06ASP.NET MVC圖片上傳前預(yù)覽簡單實現(xiàn)
這篇文章主要介紹了ASP.NET MVC圖片上傳前預(yù)覽簡單實現(xiàn)代碼,可以獲取圖片文件名和圖片字節(jié)大小,感興趣的小伙伴們可以參考一下2016-05-05