我知道这是stackoverflow中的一个旧问题。但是对我来说,这是新的,我已经搜索了一个解决方案,但是我没有找到我能理解的解决方案。我有一个插件,因为我有一些功能。现在,当事件在select options
上更改时,我想访问其中一个功能。但是我的问题是我无法从插件外部访问该功能。但是我是插件开发的新手。
这是我的插件:
(function($, window, document, undefined) {
var Spec = {
init: function(options, ele)
{
var self = this;
self.elem = ele;
self.$elem = $(ele);
self.findPro = (typeof options === 'string') ? self.findPro = options : self.findPro = options.findPro;
self.options = $.extend({}, $.fn.specpro.options, options);
if (self.options.findPro === 'latest') {
self.latestPro();
}
},
.
.
.
filter:function(filFor){
console.log($('.chzn-select').val());
}
};
$.fn.specpro = function(options) {
return this.each(function() {
var spec = Object.create(Spec);
spec.init(options, this);
});
};
$.fn.specpro.options = {
findPro: 'latest'
};
})(jQuery, window, document);
我尝试的是:
$(function(){
var mn=$('#lp').specpro({findPro:'latest'});
$('.chzn-select').chosen().change().mn.filter('latest');
});
有人可以告诉我吗?如何从插件外部调用函数filter
。
活小提琴
该函数在" spec"对象中,并且在自我启动的匿名函数的范围内:
(function($, window, document, undefined) {
... code ...
})(jQuery, window, document);
因此,只有代码在匿名函数中才能访问Spec.filter()
。要访问规格变量,它需要在全局范围中。
当"全局"范围中的某些内容中,这意味着它已连接到全局对象(在大多数情况下,这是窗口)。
所以例如
var test = {
'hello' : function (){
alert('hello world');
}
}
在功能上与:
相同window.test = {
'hello' : function (){
alert('hello world');
}
}
因此,它们都可以称为test.hello()或window.test.hello()'test'对象在全局范围(窗口)中。
现在让我们将第一个示例放在匿名函数中。
(function(){
var test = {
'hello' : function (){
alert('hello world');
}
}
// call the function
test.hello();
})();
如果您尝试此操作,它将显示警报。但是,如果您以后厌倦了致电test.hello();
,您将得到类似的东西:
参考文献:未定义测试
对象测试及其Hello()函数在匿名函数范围中,而不是全局范围。
现在,这里又有相同的功能,但是我们将测试直接连接到窗口(全局范围)。
(function(){
window.test = {
'hello' : function (){
alert('hello world');
}
}
// call the function
test.hello();
})();
现在,您可以在任何以后的时间在匿名函数之外test.hello()。您可以拥有许多级别的范围。