[英]Make Responsive Menu Plugin Work
Here is the code 这是代码
(function ( $ ) {
$.fn.responsiveMenu = function( options ) {
var settings = $.extend({
hasChildrenElement : "li.menu-item-has-children",
menuButton : ".responsive-menu-button",
}, options );
console.log( this );
$(settings.hasChildrenElement).each( function () {
$(this).append('<span class="touch-button"><i></i></span>');
});
$(settings.menuButton).on( 'click', function() {
$(this).toggleClass( 'close' );
this.toggleClass( 'showing' );
});
$('.touch-button').on( 'click', function() {
if ( $('.responsive-menu').children('li:first-child').css('display') == 'block' ) {
$(this).toggleClass( 'close' ).prev('ul').toggleClass( 'showing' );
}
});
};
}( jQuery ));
$('.responsive-menu').responsiveMenu();
I get the error app.js:37TypeError: this.toggleClass is not a function. 我收到错误app.js:37TypeError:this.toggleClass不是函数。 (In 'this.toggleClass('showing')', 'this.toggleClass' is undefined) when click on nav button. (在“ this.toggleClass('showing')'中,'this.toggleClass'未定义),当单击导航按钮时。
The code (without plugin format) works. 代码(无插件格式)有效。 Is the plugin which not. 是没有的插件。 I´m missing something but I can´t see it. 我想念一些东西,但看不到。
Thanks in advance. 提前致谢。
Ups, I´m sorry. Ups,对不起。 I was able to solve by myself the issue. 我能够自己解决问题。 Apparently is a var scope issue. 显然是var作用域问题。 If a set var varname = this; 如果设置var varname = this; outside any child function and use the varname instead of this , everything works fine. 在任何子函数之外并使用varname代替this ,一切正常。
Final code: 最终代码:
(function ( $ ) {
$.fn.responsiveMenu = function( options ) {
var settings = $.extend({
hasChildrenElement : "li.menu-item-has-children",
menuButton : ".responsive-menu-button",
}, options );
var mainElement = this;
$(settings.hasChildrenElement).each( function () {
$(this).append('<span class="touch-button"><i></i></span>');
});
$(settings.menuButton).on( 'click', function() {
$(this).toggleClass( 'close' );
mainElement.toggleClass( 'showing' );
});
$('.touch-button').on( 'click', function() {
if ( $('.responsive-menu').children('li:first-child').css('display') == 'block' ) {
$(this).toggleClass( 'close' ).prev('ul').toggleClass( 'showing' );
}
});
};
}( jQuery )); }(jQuery));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.