[英]How to implement a jQuery plugin with this feature?
So that it can be show or hide this way: 这样就可以这样显示或隐藏:
$(selector).pluginName('show')
$(selector).pluginName('hide')
The problem is how do I know which one to show or hide? 问题是如何知道要显示或隐藏哪一个 ?
I'm now doing it this way: 我现在这样做:
$.fn.pluginName = function(opts) {
var conf = $.extend({},opts);
return this.each(function() {
if(conf && 'conf' == conf.type)
{
//ClassName is defined elsewhere
new ClassName(conf,$(this));
}
else
{
//**show or hide corresponding instance**
}
});
}
You can use data
to associate your object with the DOM element it belongs to: 您可以使用data
将对象与其所属的DOM元素相关联:
$.fn.pluginName = function(opts) {
if(typeof(opts) == "string"){
this.each(function(){
// Get the associated obj
var obj = $(this).data('ClassName');
if(obj){
if(opts == "show") obj.myShowMethod();
else if (opts == "hide") obj.myHideMethod();
}
})
} else {
var conf = $.extend({},opts);
this.each(function() {
var obj = new ClassName(conf,$(this));
// Associate your object with this DOM element
$(this).data('ClassName', obj);
});
}
return this; // Don't break the chain
}
Also check out, Starter for jQuery , which uses the data
pattern to associate the object with the DOM element. 另请参阅Starter for jQuery ,它使用data
模式将对象与DOM元素相关联。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.