jQuery创建自己的插件(自定义插件)的方法

2020-05-17 06:27:09易采站长站整理


我创建了一个快速测试结构来测试我的插件(不需要单元测试库),该结构创建了许多跨区,跨区中是一些数字,紧接数字后面的是该数字的正确格式。JavaScript 测试对数字调用格式,然后比较格式化的数字与想要的结果,如果失败则显示为红色。通过该测试,我可以设置不同的测试用例,测试所有可能的格式(我已经这样做了)。我将测试页面附加到样例 下载 中,以便您为测试自己插件找到一个可能的解决方案,利用 jQuery 进行测试。


查看完成的插件


让我们看看运行中的新 NumberFormatter。我已经创建了一个简单的 web 应用程序,您可以查看 NumberFormatter 插件如何满足您的应用程序。


 

图 1. 运行中的 NumberFormatter
 

这个 Web 应用程序很简单,也很直接。当用户离开文本字段时(输入了薪水、住宅、子女信息之后),NumberFormatter 插件将相应地格式化其输入的信息。该插件使 Web 应用程序能够向用户展示统一格式的数字。还要注意,该 web 应用程序是为德国用户格式化的,因此小数点和分组符号与美国用户不一样(关于这一点,请让我展示如何更改默认值)。


清单 9. 运行中的 NumberFormatter





$(document).ready(function() {

 


// use the AlphaNumeric plug-in to limit the input
$(“.decimal”).decimal();
$(“.numeric”).numeric();


// you want to change the defaults to use the German locale
// this will change the default for every method call on the
// entire page, so you won’t have to pass in the “locale”
// argument to any function
$.fn.format.defaults.locale = “de”;
$.fn.parse.defaults.locale = “de”;


// when the salary field loses focus, format it properly
$(“#salary”).blur(function(){
$(this).format({format:”#,###.00″});
});


// when the house field loses focus, format it properly
$(“#houseWorth”).blur(function(){
$(this).format({format:”#,###”});
});
// when the kids field loses focus, format it properly
$(“#kids”).blur(function(){
$(this).format({format:”#”});
});
// calculate the tax
$(“#calculate”).click(function(){
// parse all the numbers from the fields
var salary = $(“#salary”).parse();
var house = $(“#houseWorth”).parse();
var kids = $(“#kids”).parse();
// make some imaginary tax formula
var tax = Math.max(0,(0.22*salary) + (0.03*house) – (4000*kids));
// place the result in the tax field, and then format the resulting number
// you need one intermediate step though, and that’s the “formatNumber” function
// because all numbers in JavaScript use a US locale when made into a String
// you need to convert this Number into a German locale String before
// calling format on it.
// So, the steps are:
// 1) the tax is a Number that looks like 9200.54 (US locale)
// 2) formatNumber converts this to a String of 9200,54 (German locale)
// 3) put this String in the #tax field
// 4) Call format() on this field
$(“#tax”).text($.formatNumber(tax)).format({format:”#,###”});
});