jQuery $.fn. function not defined

jQuery $.fn. function not defined

本文关键字:not defined function fn jQuery      更新时间:2023-09-26

我一直在制作我的第一个小型jQuery插件——我使用带有标准函数的javascript,但决定将其捆绑到一个带有几个选项的jQuery插件中。

这是我的jquery代码的精简版本:

(function($) {
        $.fn.responsiveNav = function( options ) {
            // Establish our default settings
            var settings = $.extend({
                selector         : '.responsive-nav'
            }, options);
            $( " " + settings.selector + " ul li" ).has( "ul" ).each(function() {
                $(this).addClass('responsive-nav-dropdown');
            });
            $( ".responsive-nav-dropdown" ).click(function() {
                $("ul",this).toggle();
            });
        }
    }(jQuery));

然后,我通过以下操作在文档中调用此函数:

$( document ).ready(function() {
    responsiveNav();
});

但这导致了一个未定义的函数错误。我猜这是某种范围界定问题,但我一直找不到任何东西来帮助我纠正这个问题。

$.fn构造用于在jQuery对象上定义一个方法。因此,你需要像这样使用你的插件:

$('#myElement').responsiveNav();

或者,您可以将其作为jQuery变量本身的一个方法:

$.responsiveNav = function( options ) { // note: no .fn
    // your code...
}
// to call it:
$.responsiveNav({ /* options */ });
(function($) {
   ///
    })(jQuery);

而不是

(function($) {
   ///
    }(jQuery));

另一件事:不要在设置中传递选择器。如果是,jQuery的实用程序是什么。

插件中的Jquery对象是this:

.each(function(i,e) {}) 
// known that e is the current element in your loop
    $.fn.responsiveNav = function( options ) {
        var this=that; 
        var settings = $.extend({selector: '.responsive-nav'}, options);
    $(that).has( "ul" ).each(function(i,e) {
        $(e).addClass('responsive-nav-dropdown');
    });
    $( ".responsive-nav-dropdown" ).click(function() {
        $("ul",this).toggle();
    });
}

您需要这样称呼它:

$("selector").responsiveNav();