DOM导航 - 意外值

时间:2014-11-12 19:52:20

标签: javascript dom

请参阅我的代码

<!DOCTYPE html>
<html>
<body>

<h1 id="H1">H1 text H1 text H1 text</h1>

<p id="P2">P2 P2 P2</p>

<script>
var Text = document.getElementById("H1").childNodes[-5].nodeValue;
document.getElementById("P2").innerHTML = Text;
</script>

</body>
</html>

当我的页面被加载时,我在段落P2中看到了相同的文字吗?

为什么我看不到&#34; undefined&#34;或&#34; null&#34;写在里面?

2 个答案:

答案 0 :(得分:0)

你H1元素只有一个子节点,一个文本节点。如果您将索引更改为0,请执行以下操作:

<!DOCTYPE html>
<html>
<body>

<h1 id="H1">H1 text H1 text H1 text</h1>

<p id="P2">P2 P2 P2</p>

<script>
var Text = document.getElementById("H1").childNodes[0].nodeValue;
document.getElementById("P2").innerHTML = Text;
</script>

</body>
</html>

你会发现它现在已经执行了,虽然我不清楚你要做什么......

答案 1 :(得分:0)

因为第二行永远不会执行。看看你的控制台。您应该看到(至少在Chrome上,其他浏览器的版本可能略有不同)Uncaught TypeError: Cannot read property 'nodeValue' of undefined

在遇到第一个错误时,您的脚本将停止执行。这就是它的工作方式:

var Text = document.getElementById("H1").childNodes[-5].nodeValue;  // <-- execution 
                                                                    // stops here
document.getElementById("P2").innerHTML = Text;       // <!-- this line never executes

发生的事情是:

document.getElementById("H1").childNodes[-5]

将返回undefined(我怀疑你知道这个,因此你的问题)。然后,您尝试访问.nodeValue上的媒体资源undefined。这会引发错误,就像您直接输入一样:

undefined.nodeValue

进入你的控制台(继续尝试)。如果它忽略了错误并继续尝试执行结果将是意外的,并可能在以后的脚本中导致进一步(和更严重)的错误。

如果您的想法是能够检查节点是否存在,那么您可以执行以下操作:

var Text = undefined; 
if (document.getElementById("H1").childNodes[-5]) {
  // undefined is falsy - so this next line won't execute and we'll get no errors
  Text = document.getElementById("H1").childNodes[-5].nodeValue;
}
// now .innerHTML will get "undefined"
document.getElementById("P2").innerHTML = Text;
<h1 id="H1">H1 text H1 text H1 text</h1>

<p id="P2">P2 P2 P2</p>