简体   繁体   中英

jQuery $.fn. function not defined

I've been making my first tiny jQuery plugin - I was using the javascript with a standard function but decided to bundle it up in to a jquery plugin with a few options.

Here's a slim down version of my jquery code:

(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));

I'm then calling this function in document ready by doing the following:

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

But this is leading to a function not defined error. I'm guessing that this is some sort of scoping issue but I haven't been able to find anything to help me rectify the issue.

The $.fn construct is used to define a method on the jQuery object. Therefore you need to use your plugin like this:

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

Alternatively you can make it a method off the jQuery variable itself:

$.responsiveNav = function( options ) { // note: no .fn
    // your code...
}

// to call it:
$.responsiveNav({ /* options */ });
(function($) {
   ///

    })(jQuery);

And not

(function($) {
   ///

    }(jQuery));

Another thing: don't pass selector in setting. If so, what is the utility of jQuery.

The Jquery object in your plugin is 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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM