我正在尝试从插件中访问数据,并直接在其中一个插件选项/默认值中使用它。从来没有这样做过,我怎么能这样做?
;(function(root, factory){
if(typeof define === 'function' && define.amd){
define(['jquery'], factory);
}else{
factory(root.jQuery);
}
}(this, function($){
var pluginName = 'somePlugin';
function Plugin(element, options){
this.obj = $(element);
this.o = $.extend({}, $.fn[pluginName].defaults, options);
this.init();
};
Plugin.prototype = {
init: function(){
// add a class to all elments with the class name 'wrap_div'
$('.wrap_div').addClass('wrapped_div');
// count the total of the newly added class(see below)
var totalElements = $('wrapped_div').length;
// for this example
alert( o.option_one );
},
destroy: function(){ }
};
$.fn[pluginName] = function(option, param) {
return this.each(function() {
var $this = $(this);
var data = $this.data(pluginName);
var options = typeof option == 'object' && option;
if(!data){
$this.data(pluginName, (data = new Plugin(this, options)))
}
if(typeof option == 'string'){
data[option](param);
}
});
};
$.fn[pluginName].defaults = {
option_one: ''
};
$[pluginName] = function() {
var $body = $(document.body);
$body[pluginName].apply($body, arguments);
}
}));
// call the plugin
$.somePlugin({
option_one: totalElements// access the var for the plugin
});