简体   繁体   中英

JavaScript error: Uncaught TypeError: Cannot read property 'left' of undefined

This is a really annoying error and there seems to be various questions about this console error. It doesn't give me a whole lot to work with in the console using chrome.

 /**
     * Dropdown menu positioning
     */
    loc.dropMenuPositioning = function (){
        var dropMenu = $('.js-dropdown-item-wrap');
        var mainNavigationOffset = $('.js-nav-container > ul').offset();
        var mainNavigationPosition = mainNavigationOffset.left;
        dropMenu.css({'left' : mainNavigationPosition - 60});
    };

Sorry, i don't have much more to go with on this question. Any help would be greatly appreciated. Thank you.

You are reading the property left from an object returned in the previous row. The line that fails is:

var mainNavigationPosition = mainNavigationOffset.left;

The error means that mainNavigationOffset is undefined.

Because mainNavigationOffset is set as:

var mainNavigationOffset = $('.js-nav-container > ul').offset();

it is possible that jquery was not able to get the offset of the element $('.js-nav-container > ul').

As stated by the jquery documentation:

Note: jQuery does not support getting the offset coordinates of hidden elements or accounting for borders, margins, or padding set on the body element.

While it is possible to get the coordinates of elements with visibility:hidden set, display:none is excluded from the rendering tree and thus has a position that is undefined.

Check that the element is actually visible.

Another option (that seems what really happened) is that the jquery expression:

$('.js-nav-container > ul')

is not returning any element.

To see if the element is visible, you can use the chrome dev tool:

display must not be equals to none 显示不应等于无

visibility must be equals to visible 可见性应等于可见

Or you can simply execute in the console:

$('.js-nav-container > ul').css("display");
$('.js-nav-container > ul').css("visibility");

Try this, jQuery doc

dropMenu.offset({ left: mainNavigationPosition - 60 });

Otherwise, you might need to set the position to absolute or relative:

link

Check if your jQuery version is up to 1.2, the .offset() method may not work in older versions.

jQuery 1.2 change log

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