简体   繁体   English

jQuery的/ JavaScript的:未捕获的TypeError?

[英]jquery / javascript: Uncaught TypeError?

hey guys, i wrote a little custom animated scroll function... 大家好,我写了一些自定义的动画滚动功能...

function scroll(selector, animate, viewOffset) {

    pageOffset = selector.offset();
    scrollPos = pageOffset.top - viewOffset;

    if (animate) {

        $('html, body').animate({scrollTop : scrollPos + 'px'}, {
            duration: 'slow', // how fast we are animating
            easing: 'easeOutQuint', // the type of easing
            complete: function() { }
        });

    } else {
        $('html, body').scrollTop( scrollPos );
    }

}

I call it with scroll($('#something'), false, 30); 我用scroll($('#something'), false, 30);称呼它scroll($('#something'), false, 30);

It actually works, however sometimes it's a little bit buggy and the function doesn't properly work. 它实际上可以工作,但是有时会有点bug,并且该功能不能正常工作。 I always call the scroll() function on a click-event. 我总是在点击事件上调用scroll()函数。

The biggest problem I have is that on page load my console tells me the following line. 我最大的问题是,在页面加载时,我的控制台告诉我以下行。

Uncaught TypeError: Cannot read property 'top' of null (script.js line 191 which is line 3 in my example above) 未捕获到的TypeError:无法读取null的属性“ top”(script.js第191行,即上述示例中的第3行)

Any idea what could cause this error? 知道什么可能导致此错误吗? the scroll() function is not even called on dom-ready or on-load. 甚至在dom-ready或加载时也不调用scroll()函数。 It's just called on specific click-events. 只是在特定的点击事件上调用它。

thank you for your help 谢谢您的帮助

您确定在页面上定义了#selector吗?

Shouldn't it be: 不应该是:

pageOffset = $(selector).offset();

?

I usually get same "mysterious errors" with selector mistypes. 我通常会因选择器类型错误而遇到相同的“神秘错误”。

Wrap all code in your function with try/catch statement and try to debug it. 使用try / catch语句包装函数中的所有代码,然后尝试对其进行调试。 There are debug tools in almost all major browsers. 几乎所有主流浏览器中都有调试工具。 Set a breakpoint inside catch statement and then your script hit there look at pageOffset and selector variables. 在catch语句内设置一个断点,然后在脚本中点击pageOffset和选择器变量。

PS: PhpStorm has the best debugger for JavaScript a ever seen. PS:PhpStorm拥有有史以来最好的JavaScript调试器。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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