开发者问题收集

javascript 错误‘无法读取未定义的属性’

2015-08-04
24723

javascript、html 和 css 在此 jsfiddle 中可以正常工作 但当输入到 html 文件中时,如下所示:

<!doctype html>
<html>
  <head>
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="chrome=1">
        <script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.11.3.min.js"></script>
        <script type="text/javascript">
            var target = $(".mypara").offset().top;
            var interval = setInterval(function() {
                if ($(window).scrollTop() >= target) {
                    alert("made it!");
                    clearInterval(interval);
                    }
            }, 250);
        </script>
        <style>
            body {
            background-color: linen;
            height: 1000px;
            }
            p {
             color: blue;
              margin-top: 500px;
            }
        </style>

    </head>
    <body>
     <p class="mypara">asdfasdfasf</p>
    </body>
</html>

chrome 控制台显示此错误

Uncaught TypeError: Cannot read property 'top' of undefined(anonymous function) @ index - Copy.html:8

此错误涉及第 8 行:

var target = $(".mypara").offset().top;

有人能帮我理解原因吗?

2个回答

将您的代码包装在

$(document).ready (function (){
    // code here
});

您尝试在元素存在之前访问 DOM 中的元素,因此当您尝试访问该类时,该项目尚不存在。或者将您的脚本移到 html 中的元素下方

在 fiddle 中工作,因为它们会根据您的设置包装您的代码,我相信默认为 domready

Sean Wessell
2015-08-04
<!doctype html>
<html>
    <head>
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="chrome=1">

        <style>
            body {
                background-color: linen;
                height: 1000px;
            }
            p {
                color: blue;
                margin-top: 500px;
            }
        </style>
    </head>

    <body>
        <p class="mypara">asdfasdfasf</p>
        <p class="mypara">Include js files to be at the bottom so that it would be the one to be loaded accordingly</p>
        <script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.11.3.min.js"></script>
        <script type="text/javascript">
            // if document is ready then
            // its the only time to execute
            // process withing the block
            $(document).ready(function() {
                var target = $(".mypara").offset().top;
                var interval = setInterval(function() {
                    if ($(window).scrollTop() >= target) {
                        alert("made it!");
                        clearInterval(interval);
                    }
                }, 250);
            });

            </script>
    </body>
</html>
Oli Soproni B.
2015-08-04