syg*_*ad1 4 methods jquery plugins public creation
我已经创建了一个插件,可以使用DIV将HTML选择框转换为自定义下拉列表.
一切运作良好,但我想让它好一点.看到我的jsFiddle
在插件的最后我有2个方法,slideDownOptions和slideUpOptions,我想在插件之外使这些可用,以便其他事件可以触发操作.
我有点困惑如何做到这一点,更具体地说,如何从插件内部和插件外部调用方法.
任何帮助总是赞赏
Inf*_*pse 13
考虑使用面向对象的代码重构您的插件.有了这个,您可以为您的插件制作API,如jQuery UI API.所以你可以访问插件方法,如:
$('select').customSelect(); // apply plugin to elements
$('select').customSelect('resetOpacity'); // call method resetOpacity();
$('select').customSelect('setOpacity', 0.5); // call method with arguments
Run Code Online (Sandbox Code Playgroud)
用于创建此类插件的基本模板如下所示:
// plugin example
(function($){
// custom select class
function CustomSelect(item, options) {
this.options = $.extend({
foo: 'bar'
}, options);
this.item = $(item);
this.init();
}
CustomSelect.prototype = {
init: function() {
this.item.css({opacity:0.5});
},
resetOpacity: function() {
this.setOpacity('');
},
setOpacity: function(opacity) {
this.item.css({opacity:opacity});
}
}
// jQuery plugin interface
$.fn.customSelect = function(opt) {
// slice arguments to leave only arguments after function name
var args = Array.prototype.slice.call(arguments, 1);
return this.each(function() {
var item = $(this), instance = item.data('CustomSelect');
if(!instance) {
// create plugin instance and save it in data
item.data('CustomSelect', new CustomSelect(this, opt));
} else {
// if instance already created call method
if(typeof opt === 'string') {
instance[opt].apply(instance, args);
}
}
});
}
}(jQuery));
// plugin testing
$('select').customSelect();
Run Code Online (Sandbox Code Playgroud)
工作JS在这里小提琴:http://jsfiddle.net/XsZ3Z/
| 归档时间: |
|
| 查看次数: |
6804 次 |
| 最近记录: |