[英]Make Responsive Menu Plugin Work
這是代碼
(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();
我收到錯誤app.js:37TypeError:this.toggleClass不是函數。 (在“ this.toggleClass('showing')'中,'this.toggleClass'未定義),當單擊導航按鈕時。
代碼(無插件格式)有效。 是沒有的插件。 我想念一些東西,但看不到。
提前致謝。
Ups,對不起。 我能夠自己解決問題。 顯然是var作用域問題。 如果設置var varname = this; 在任何子函數之外並使用varname代替this ,一切正常。
最終代碼:
(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));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.