1、基础写法
我们平时用jquery的方法:
$( "a" ).css( "color", "red" );
这里的css方法其实挂载在 $.fn上的,所以最简单的一个jquery插件就是往 $.fn上挂载自定义方法
$.fn.greenify = function() {
this.css( "color", "green" );
};
$( "a" ).greenify(); // Makes all the links green.
2、链式调用
链式调用只要在上面挂在的函数内部返回this就行了
$.fn.greenify = function() {
this.css( "color", "green" );
return this;
}
$( "a" ).greenify().addClass( "greenified" );
3、用立即执行函数保护变量私有性
为了保护$不被别的代码污染,可以将插件写在立即执行函数里
(function ( $ ) {
$.fn.greenify = function() {
this.css( "color", "green" );
return this;
};
}( jQuery ));
4、插件接受选项
如果想让你的插件可配置化,即可以让插件使用者传入自定义参数,可以如下写:
(function ( $ ) {
$.fn.greenify = function( options ) {
// This is the easiest way to have default options.
var settings = $.extend({
// These are the defaults.
color: "#556b2f",
backgroundColor: "white"
}, options );
// Greenify the collection based on the settings variable.
return this.css({
color: settings.color,
backgroundColor: settings.backgroundColor
});
};
}( jQuery ));
5、一个完整Demo
将页面上的a元素内容追加url
(function( $ ) {
$.fn.showLinkLocation = function() {
this.filter( "a" ).each(function() {
var link = $( this );
link.append( " (" + link.attr( "href" ) + ")" );
});
return this;
};
}( jQuery ));
// Usage example:
$( "a" ).showLinkLocation();
/*
<!-- Before plugin is called: -->
<a href="page.html">Foo</a>
<!-- After plugin is called: -->
<a href="page.html">Foo (page.html)</a>
*/