[英]JavaScript - DOM nodeValue problem
Why the function NodeValue__Two()
show null
? 为什么函数NodeValue__Two()
显示null
? To me, it should show the same thing as the function NodeValue__One()
. 对我来说,它应该显示与NodeValue__One()
函数相同的东西。
I have tested this on IE6. 我已经在IE6上进行了测试。
<html>
<body>
<script language="JavaScript">
function NodeValue__One()
{
alert(myNodeOne.childNodes(0).nodeValue);//This is OK
}
function NodeValue__Two()
{
alert(document.all[6].nodeValue);//This is NOT OK
}
</script>
<p>This PARAGRAPH has two nodes,
<b id="myNodeOne">Node One Text</b>, and
<b id="myNodeTwo">Node Two Text</b>.
<input id="txt1" type="text" value="Damn!!!" />
</p>
<button onclick="NodeValue__One();">Node Value 1</button></br>
<button onclick="NodeValue__Two();">Node Value 2</button>
</body>
</html>
The All
array is an array of Elements. All
数组是Elements的数组。 Elements do not have a value in the nodeValue. 元素在nodeValue中没有值。
On the other hand childNodes
will contain both Elements and TextNodes. 另一方面, childNodes
将同时包含Elements和TextNodes。
Its really hard to get the index of All
correct since the number of actual elements listed in All can vary from what you are seeing in the HTML. 很难正确地找到All
的索引,因为All
列出的实际元素的数量可能与您在HTML中看到的有所不同。 For example dispite there being no HEAD or TITLE Element present in the HTML text, they will be present in the DOM. 例如,尽管HTML文本中没有HEAD或TITLE元素,但它们将出现在DOM中。
Both approaches are deprecated and not safe. 两种方法都已弃用并且不安全。 It would be better if you gave your elements unique identifiers and used getElementById
function to find elements in the DOM: 如果为元素提供唯一的标识符,并使用getElementById
函数在DOM中查找元素会更好:
var element = document.getElementById('id_of_element');
One reason may be that you have erroneously assumed that "This Paragraph has two nodes". 原因可能是您错误地假定“本段有两个节点”。 It has at least six, including the three text nodes containing "This PARAGRAPH has two nodes,", ", and" and ".". 它至少有六个,包括三个文本节点,其中包含“此PARAGRAPH具有两个节点”,“和”和“。”。
使用document.all[6].text
这将为您提供Node Two Text
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.