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

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

 


// This is a function, because you are NOT passing any selector to the function
// The plug-in developer must determine what page elements they want to take action on.
// This is usually accomplished by the plug-in developer requiring the page elements
// to contain a certain class name.


<div class=”anotherThing”>


// This hypothetical plug-in developer would document that his plug-in only works
// on elements with the class “anotherThing”
$.anotherThing();


 


从这些描述中判断,插件使用的似乎是方法,因为您需要让用户告诉您他们希望格式化哪些页面元素。清单 2 展示了现在插件的代码。



清单 2. 方法定义





jQuery.fn.format = function();

 


// You would call your plug-in like this (at this point)
$(“#myText”).format();


 


当然,您的函数不可能是放之四海而皆准的插件,因为您处理的是国际化情况,无法自动指出希望格式化文本的国家或者需要的格式。因此,您必须稍微修改插件以接收某些选项。格式化方法中需要两个选项:数字应该使用的格式(例如,#,### 以及 #,###.00)和本地语言环境(本地语言环境是一个简单的 2 字符国家代码,用于确定要使用的国际数字格式)。


您还需要让插件尽可能的易于使用,因为您必须提高插件的成功几率。这意味着您应该继续定义一些默认的选项,使用户在不想传入选项时不需要这样做。我编写插件的所在地是美国,这里使用的是世界上最常见的数字格式,我的默认语言环境是 “us”,格式默认为 “#,###.00”,因此货币自然要使用该默认值。


 


 


清单 3. 允许在插件中使用选项






jQuery.fn.format = function(options) {

 


// the jQuery.extend function takes an unlimited number of arguments, and each
// successive argument can overwrite the values of the previous ones.
// This setup is beneficial for defining default values, because you define
// them first, and then use the options passed into the method as the
// second argument. This allows the user to override any default values with their
// own in an easy-to-use setup.
var options = jQuery.extend( {


format: “#,###.00”,
locale: “us”


}, options);


 


创建插件框架的最后一步是正确处理传入方法的选定元素。回想一下上例您会发现,选定元素可以是单页面元素,或者是多页面元素。您必须等效地处理它们。同样,回想一下 jQuery 插件规则,