在 jQuery 插件的命名函数中使用 "this"
Using "this" inside named function on a jQuery plugin
我正在尝试编写一个简单的 jQuery 插件,我需要一些代码来 运行 加载和 window 调整大小,所以我在插件中编写了一个函数。
jQuery(文档).ready(函数($) {
(function( $ ) {
$.fn.responsiveNav = function() {
function enable_responsive_nav() {
if( this.hasClass('class') ) {
//do stuff
}
}
$(window).resize(function(e) {
enable_responsive_nav();
});
enable_responsive_nav();
return this;
};
}( jQuery ));
$('nav').responsiveNav();
问题是 'this' 函数内部似乎没有被识别。我尝试将其作为函数参数传递:
enable_responsive_nav( this )
...但是我在控制台上收到一条错误消息 hasClass() 'is not a function'.
我想我可以在没有函数的情况下完成它,然后在插件外部绑定 window 调整大小事件,但我试图将它保持在一个调用中,我确信我所做的想念很简单。
I tried passing it as a function argument:
enable_responsive_nav( this )
让我们跟着链条走:
jQuery 将使用 this
调用您的事件回调,引用 DOM 元素 (不是 jQuery 对象)事件被迷上了。所以你可以这样做:
enable_responsive_nav( $(this) );
...与
if( arg.hasClass('class') ) {
//do stuff
}
或
enable_responsive_nav.call(this);
和
if($(this).hasClass('class') ) {
//do stuff
}
一种常见的解决方案是在this
具有预期值的范围内创建一个名为that
或self
的局部变量,然后在内部函数的范围:
(function( $ ) {
$.fn.responsiveNav = function() {
var self = this; // local variable
function enable_responsive_nav() {
if( self.hasClass('class') ) { // self is in scope
//do stuff
}
}
$(window).resize(function(e) {
enable_responsive_nav();
});
enable_responsive_nav();
return this;
};
}( jQuery ));
$('nav').responsiveNav();
我正在尝试编写一个简单的 jQuery 插件,我需要一些代码来 运行 加载和 window 调整大小,所以我在插件中编写了一个函数。
jQuery(文档).ready(函数($) {
(function( $ ) {
$.fn.responsiveNav = function() {
function enable_responsive_nav() {
if( this.hasClass('class') ) {
//do stuff
}
}
$(window).resize(function(e) {
enable_responsive_nav();
});
enable_responsive_nav();
return this;
};
}( jQuery ));
$('nav').responsiveNav();
问题是 'this' 函数内部似乎没有被识别。我尝试将其作为函数参数传递:
enable_responsive_nav( this )
...但是我在控制台上收到一条错误消息 hasClass() 'is not a function'.
我想我可以在没有函数的情况下完成它,然后在插件外部绑定 window 调整大小事件,但我试图将它保持在一个调用中,我确信我所做的想念很简单。
I tried passing it as a function argument:
enable_responsive_nav( this )
让我们跟着链条走:
jQuery 将使用 this
调用您的事件回调,引用 DOM 元素 (不是 jQuery 对象)事件被迷上了。所以你可以这样做:
enable_responsive_nav( $(this) );
...与
if( arg.hasClass('class') ) {
//do stuff
}
或
enable_responsive_nav.call(this);
和
if($(this).hasClass('class') ) {
//do stuff
}
一种常见的解决方案是在this
具有预期值的范围内创建一个名为that
或self
的局部变量,然后在内部函数的范围:
(function( $ ) {
$.fn.responsiveNav = function() {
var self = this; // local variable
function enable_responsive_nav() {
if( self.hasClass('class') ) { // self is in scope
//do stuff
}
}
$(window).resize(function(e) {
enable_responsive_nav();
});
enable_responsive_nav();
return this;
};
}( jQuery ));
$('nav').responsiveNav();