这是代码
(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('显示')','this.toggleClass'未定义),点击导航按钮。
代码(没有插件格式)有效。插件不是。我错过了一些东西,但我看不到它。
提前致谢。
答案 0 :(得分:0)
起来,对不起。我能够自己解决这个问题。显然是一个范围问题。如果在任何子函数之外设置 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));