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

时间:2015-08-04 01:35:35

标签: javascript jquery html css

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 console出现此错误

  

未捕获的TypeError:无法读取属性&#39; top&#39; of undefined(匿名函数)@index - Copy.html:8

此错误指的是第8行:

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

有人可以帮助我理解为什么吗?

2 个答案:

答案 0 :(得分:3)

将代码包装在

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

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

中的元素下面

在小提琴中工作会导致你根据你的设置包装你的代码,默认情况下我认为是

答案 1 :(得分:0)

<!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>
相关问题