使用 jQuery(中级),第 2 部分: 创建自己的插件
2010-01-14 00:00:00 来源:WEB开发网
清单 1. jQuery 插件方法/函数
// This is a method because you can pass any type of selector to the method and it
// will take some action on the results of the selector. In this case, it will
// doSomething() on the page element with an ID of myExample
$("#myExample").doSomething();
// This is also a method, even though you are passing the entire page body to
// the method, because you are still passing a selector
$("body").doSomethingElse();
// 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();
编缉推荐阅读以下文章
- 使用 jQuery(中级),第 1 部分: 使用插件创建和扩展 jQuery 函数
- 使用 jQuery,第 3 部分: 用 jQuery 和 Ajax 构建富 Internet 应用程序
- 使用 jQuery,第 2 部分: 构建未来的 Web 应用程序
- 使用 jQuery,第 1 部分: 将桌面应用程序引入浏览器
更多精彩
赞助商链接