我正在开发一个插件,将对象添加到插件后,我想从外部调用一些事件到同一对象,我该怎么做
(function ($, undefined) {
jQuery.fn.pluginname = function (options) {
var set = $.extend({
opacity: 0.5
}, options);
//if(options.type)
var cdiv = this;
cdiv.css("opacity",set.opacity);
function callthis()
{
cdiv.css("display","none");
}
}
})(jQuery);
jQuery("#first").pluginname({opacity:0.5});
jQuery("#second").pluginname({opacity:0.5});
// call this function later
jQuery("#first").pluginname("callthis");
通常的方法是让您的插件接受“方法”作为字符串参数,例如:
jQuery("#first").pluginname("callThis");
在插件内部,您可以将该请求路由到该函数。
通常,您还希望将最初使用的选项存储在闭包之外的其他位置。data
对此很有用。
通常,您有一种"destroy"
从元素中删除插件的方法。
所以:
(function ($, undefined) {
var methods = {
init: function(options) {
// Determine options
var opts = $.extend({
opacity: 0.5
}, options);
// Remember them
this.data("pluginname", opts);
// Initial stuff
this.css("opacity", opts.opacity);
},
callThis: function(opts) {
// Use 'opts' if relevant
this.css("display","none");
},
destroy: function(opts) {
this.removeData("pluginame");
this.css("display", "").css("opacity", "");
}
};
jQuery.fn.pluginname = function (options) {
var method, args;
// Method?
if (typeof options === "string") {
// Yes, grab the name
method = options;
// And arguments (we copy the arguments, then
// replace the first with our options)
args = Array.prototype.slice.call(arguments, 0);
// Get our options from setup call
args[0] = this.data("pluginname");
if (!args[0]) {
// There was no setup call, do setup with defaults
methods.init.call(this);
args[0] = this.data("pluginname");
}
}
else {
// Not a method call, use init
method = "init";
args = [options];
}
// Do the call
methods[method].apply(this, args);
};
})(jQuery);
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句