脚本宝典收集整理的这篇文章主要介绍了jquery 插件,脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。
jQuery插件学习
例1:基础
$.fn.maxHeight = function() {
VAR max = 0;
this.each(function() {
max = Math.max(max, $(this).height());
});
return max;
};
})(jquery);
var tallest = $('div').maxHeight();//返回最高的div元素@H_304_47@
$.fn.lockDimensions = function(tyPE) {
return this.each(function() {
var $this = $(this);
if(!type || type = 'width') {
$this.width($this.width());
}
if(!type || type == 'width') {
$this.height($this.height());
}
});
};
})(jQuery);
$('div').lockDimensions('width').css('color', 'red');
例3:默认值和选项
$.fn.tooltip = function(options) {
//创建一些默认值,拓展任何被提供的选项
//$.extend(target,[object1,object2]):合并一个或两个object到target中
var setting = $.extend({
'location': 'top',
'background-color': 'blue'
}, options);
return this.each(function() {
//Tooltip插件代码
});
};
})(jQuery);
//调用toolTip插件时覆写了默认设置中的location选项,background-color选项保持默认值。
$('div').tooltip({
'location': 'left'
});
这是一个很灵活的方式,提供一个高度可配置的插件,而无需开发人员定义所有可用的选项。
例4:插件方法:
var methods = {
init: function (options) {
//code
},
show: function() {
//code
},
hide: function() {
//code
},
update: function (content) {
// !!!
}
};
$.fn.tooltip = function(method) {
//方法调用
if(methods[method]) {
return methods[method].apply(this,Array.PRototype.slice.call(arguments, 1));
} else if (typeof method === 'object' || !method) {
return methods.init.apply(this,arguments);
} else {
$.error('Method' + method + '不存在');
}
};
))(jQuery);
//调用init方法
$('div').tooltip();
//调用init方法
$('div').tooltip({
foo: 'bar'
});
//调用hide方法
$('div').tooltip('hide');
//调用Update方法
$('div').tooltip('update', 'this is the new tooltip content!');
这种插件架构允许封装所有的方法在父包中,通过传递该方法的字符串名称和额外的此方法需要的参数来调用它们。这种方法的封装和架构类型是jQuery插件社区的标准。
例5:事件:
var methods = {
init: function (options) {
return this.each(function () {
$(window).bind('resize.tooltip', methods.reposition);
});
},
destory: function() {
return this.each(function() {
$(window).unbind('.tooltip');
});
},
reposition: function () {
//...
},
show: function() {
//code
},
hide: function() {
//code
},
update: function (content) {
// !!!
}
};
$.fn.tooltip = function(method) {
//方法调用
if(methods[method]) {
return methods[method].apply(this,Array.prototype.slice.call(arguments, 1));
} else if (typeof method === 'object' || !method) {
return methods.init.apply(this,arguments);
} else {
$.error('Method' + method + '不存在');
}
};
))(jQuery);
$('#fun').tooltip();
//一段时间之后。。。 。。。
$('#fun').tooltip('destory');
例6:数据