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

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

return this.each(function(){
// rest of the plug-in code here


// define the defaults here as an object in the plug-in
jQuery.fn.format.defaults = {
format: “#,###.00”,
locale: “us”
}; // don’t forget the semi-colon



这是创建插件的最后一个步骤!这样您就有了一个不错的插件,可以进行最后的测试了。清单 8 展示了您可以放入本文的完整插件,以便您查看这些部分是如何变为一个整体的。此外还包含了 parse() 函数,到目前为止我还没有讨论过该函数,但是它包含在插件中(我没有详细介绍插件处理格式化的部分,因为它们不在本文讨论之列。样例中包含了该部分,插件本身当然也有)。


清单 8. NumberFormatter 插件





(function(jQuery) {

 


function FormatData(valid, dec, group, neg) {
this.valid = valid;
this.dec = dec;
this.group = group;
this.neg = neg;
};


function formatCodes(locale) {
// format logic goes here
return new FormatData(valid, dec, group, neg);
};


jQuery.fn.parse = function(options) {


var options = jQuery.extend({},jQuery.fn.parse.defaults, options);


var formatData = formatCodes(options.locale.toLowerCase());


var valid = formatData.valid;
var dec = formatData.dec;
var group = formatData.group;
var neg = formatData.neg;


var array = [];
this.each(function(){


var text = new String(jQuery(this).text());
if (jQuery(this).is(“:input”))
text = new String(jQuery(this).val());



// now we need to convert it into a number
var number = new Number(text.replace(group,”).replace(dec,”.”).replace(neg,”-“));
array.push(number);
});


return array;
};


jQuery.fn.format = function(options) {


var options = jQuery.extend({},jQuery.fn.format.defaults, options);


var formatData = formatCodes(options.locale.toLowerCase());


var valid = formatData.valid;
var dec = formatData.dec;
var group = formatData.group;
var neg = formatData.neg;


return this.each(function(){
var text = new String(jQuery(this).text());
if (jQuery(this).is(“:input”))
text = new String(jQuery(this).val());


// formatting logic goes here


if (jQuery(this).is(“:input”))
jQuery(this).val(returnString);
else
jQuery(this).text(returnString);
});
};
jQuery.fn.parse.defaults = {
locale: “us”
};


jQuery.fn.format.defaults = {
format: “#,###.00”,
locale: “us”
};
})(jQuery);



测试插件


创建插件的最后一步是全面测试它。用户在插件中发现 bug 会让他们很恼火。用户不会去修复它,他们会快速放弃使用它。如果有几个这类用户再加上一些糟糕的评论,您的插件很快就会石沉大海。此外,这是一个很好的互惠行为 —— 您希望自己使用的插件都经过了很好的测试,那么您也应该提供经过良好测试的插件。