jquery插件给我的感觉清一色的清洁,简单。如Jtip,要使用它的功能,只需要在你的元素的class上加上Jtip,并引入jtip.js及其样式即可以了。其他事情插件全包。我喜欢jquery的一个重要原因是发现她已经有了很多很好,很精彩的插件。写一个自己的jQuery插件是非常容易的,如果你按照下面的原则来做,可以让其他人也容易地结合使用你的插件.
- 为你的插件取一个名字,在这个例子里面我们叫它"foobar".
- 创建一个像这样的文件:jquery.[yourpluginname].js,比如我们创建一个jquery.foobar.js
- 创建一个或更多的插件方法,使用继承jQuery对象的方式,如:
jQuery.fn.foobar = function() {
// do something
};
- 可选的:创建一个用于帮助说明的函数,如:
jQuery.fooBar = {
height: 5,
calculateBar = function() { ... },
checkDependencies = function() { ... }
};
jQuery.fn.foobar = function() {
// do something
jQuery.foobar.checkDependencies(value);
// do something else
};
- 可选的l:创建一个默认的初始参数配置,这些配置也可以由用户自行设定,如:
jQuery.fn.foobar = function(options) {
var settings = {
value: 5,
name: "pete",
bar: 655
};
if(options) {
jQuery.extend(settings, options);
}
};
$("...").foobar();
$("...").foobar({
value: 123,
bar: 9
});
$("input[@type='checkbox']").each(function() {
this.checked = true;
// or, to uncheck
this.checked = false;
// or, to toggle
this.checked = !this.checked;
});
$.fn.check = function() {
return this.each(function() {
this.checked = true;
});
};
$("input[@type='checkbox']").check();
$.fn.check = function(mode) {
var mode = mode || 'on'; // if mode is undefined, use 'on' as default
return this.each(function() {
switch(mode) {
case 'on':
this.checked = true;
break;
case 'off':
this.checked = false;
break;
case 'toggle':
this.checked = !this.checked;
break;
}
});
};
$("input[@type='checkbox']").check();
$("input[@type='checkbox']").check('on');
$("input[@type='checkbox']").check('off');
$("input[@type='checkbox']").check('toggle');
$.fn.rateMe = function(options) {
var container = this; // instead of selecting a static container with $("#rating"), we now use the jQuery context
var settings = {
url: "rate.php"
// put more defaults here
// remember to put a comma (",") after each pair, but not after the last one!
};
if(options) { // check if options are present before extending the settings
$.extend(settings, options);
}
// ...
// rest of the code
// ...
return this; // if possible, return "this" to not break the chain
});