簡體   English   中英

“未定義不是函數,並且”無法讀取未定義的屬性“ init””

[英]“Undefined is not a function and ”Cannot read property 'init' of undefined"

我正在嘗試獲取此javascript代碼以打開/關閉megamenu部分以與Wordpress配合使用:

它確實適用於html模板。 我還創建了一個可以工作的Walker。

 var swMegaMenu = (function() { var $listItems = $( '#sw-hrmenu > ul > li' ), // Uncaught TypeError: Undefined is not a function $menuItems = $listItems.children( 'a' ), $body = $( 'body' ), current = -1; function init() { $menuItems.on( 'click', open ); $listItems.on( 'click', function( event ) { event.stopPropagation(); } ); } function open( event ) { if( current !== -1 ) { $listItems.eq( current ).removeClass( 'sw-hropen' ); } var $item = $( event.currentTarget ).parent( 'li' ), idx = $item.index(); if( current === idx ) { $item.removeClass( 'sw-hropen' ); current = -1; } else { $item.addClass( 'sw-hropen' ); current = idx; $body.off( 'click' ).on( 'click', close ); } return false; } function close( event ) { $listItems.eq( current ).removeClass( 'sw-hropen' ); current = -1; } return { init : init }; })(); 

和(頁腳中的摘要):

 <script> (function($) { // Uncaught TypeError: Cannot read property 'init' of undefined swMegaMenu.init(); })(jQuery); </script> 

任何想法如何解決此問題?

我認為您需要這樣做:

        var swMegaMenu = (function () {

        var $listItems = $('#sw-hrmenu > ul > li'), // Uncaught TypeError: Undefined is not a function
            $menuItems = $listItems.children('a'),
            $body = $('body'),
            current = -1;


        function open(event) {

            if (current !== -1) {
                $listItems.eq(current).removeClass('sw-hropen');
            }

            var $item = $(event.currentTarget).parent('li'),
                idx = $item.index();

            if (current === idx) {
                $item.removeClass('sw-hropen');
                current = -1;
            }
            else {
                $item.addClass('sw-hropen');
                current = idx;
                $body.off('click').on('click', close);
            }

            return false;

        }

        function close(event) {
            $listItems.eq(current).removeClass('sw-hropen');
            current = -1;
        }

        return { init: init };

    })();

    swMegaMenu.initialize = function()
    {
        $menuItems.on('click', open);
        $listItems.on('click', function (event) { event.stopPropagation(); });
    }

在頁腳中:

<script>
        (function($) { // Uncaught TypeError: Cannot read property 'init' of undefined
            swMegaMenu.initialize();
        })(jQuery);

</script>

由於沒有提供標記,因此我無法驗證代碼,但是應該是這樣的。

您使用的是WordPress,默認情況下它在noConflict()模式下包含jQuery。 noConflict()模式下,jQuery的$全局快捷方式不可用。

結果,您將需要將(function()更改為(function($) ,將結尾()更改為(jQuery)

WordPress Codex中閱讀有關noConflict()包裝器的更多信息。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM