我创建了一个简单的jQuery扩展(这是我的第一个).
(function($){
var MyClass = function(opt){
//..
};
//one of the methods of my extension
$.fn.myExtension = function(opt){
this._ext = new MyClass(opt);
return this;
};
$.fn.myExtensionOtherMethod = function(){
if(this._ext){
//do something ..
}
return this;
};
}(jQuery));
//using ..
$(document).ready(function(){
$('#selector').myExtension({
//options ..
});
$('#selector').myExtensionOtherMethod();
});
Run Code Online (Sandbox Code Playgroud)
当我调用方法时$('#selector').myExtensionOtherMethod();,this不包含this._ext变量.我知道这是其他范围,但我知道有两种方法可以在两种方法中访问该变量.我可以这样做吗?
这实际上不是范围问题。这是因为 jQuery 原型$.fn为您提供了一个 jquery 对象,如this. 即使您每次都选择相同的元素,将新的 jQuery 对象设置为上下文,以便该属性消失。您可以将该属性放在 DOM 元素上并实现您想要的结果。
(function($) {
var MyClass = function(opt) {};
//one of the methods of my extension
$.fn.myExtension = function(opt) {
this[0]._ext = new MyClass(opt);
return this;
};
$.fn.myExtensionOtherMethod = function() {
if (this[0]._ext) {
//do something ..
}
return this;
};
}(jQuery));
//using ..
$(document).ready(function() {
$('#selector').myExtension({
//options ..
});
$('#selector').myExtensionOtherMethod();
});
Run Code Online (Sandbox Code Playgroud)
这只是上面的一个简单示例。如果您的选择器找到多个元素,您应该循环遍历它们。但我只抓取了第一个索引,因为你是按 ID 选择的。
小提琴:https://jsfiddle.net/AtheistP3ace/gd1ehk0d/
正如 @charlietfl 上面提到的,我同意这个评论。很高兴解释为什么你所做的不起作用,但可能有更好的方法来实现你正在寻找的东西。
| 归档时间: |
|
| 查看次数: |
49 次 |
| 最近记录: |