为什么警报没有价值?

时间:2012-08-30 01:33:04

标签: javascript

<title>New Web Project</title>
        <script type="text/javascript">
            var paras = document.getElementsByTagName("p");
            for (var i=0; i< paras.length; i++) {
            var title_text = paras[i].getAttribute("title");
            if (title_text != null) {
                alert(title_text);
                }
            }

        </script>
    </head>
    <body>
        <h1>New Web Project Page</h1>
        <p title="test"> This is just a test</p>
    </body>

为什么警报没有价值?我觉得它应该弹出文本test

2 个答案:

答案 0 :(得分:6)

因为评估script时,p 尚未

如果您在 script之后添加p权利,则在p已呈现时,它会按预期显示alert:< / p>

<p title="test"> This is just a test</p>
<script type="text/javascript">
  var paras = document.getElementsByTagName("p");
  for (var i=0; i< paras.length; i++) {
    var title_text = paras[i].getAttribute("title");
    if (title_text != null) {
      alert(title_text);
    }
}
</script>

请参阅 DEMO

答案 1 :(得分:2)

因为在呈现html元素之前初始化脚本。

将脚本移至底部或等待DOM。像这样:

<html>
<head>
<title>New Web Project</title>
    <script type="text/javascript">
        window.onload = function(){
            var paras = document.getElementsByTagName("p");
            for (var i=0; i< paras.length; i++) {
            var title_text = paras[i].getAttribute("title");
            if (title_text != null) {
                alert(title_text);
                }
            }
        }
    </script>
</head>
<body>
    <h1>New Web Project Page</h1>
    <p title="test"> This is just a test</p>
</body>
</html>