我是javascript的新手。我正在使用nodeValue从节点返回文本。由于返回的是null,因此我尝试使用firstChild.nodeValue。但是,现在它说:无法读取null的属性“ nodeValue”,这是代码:-
<head>
<script type="text/javascript" src="get.js"></script>
</head>
<body>
<ul id="eventsList">
<li>List 1</li>
<li>List 2</li>
<li><a href="http://www.google.com">Linked item to Google</a></li>
<li>List 4</li>
</ul>
</body>
get.js:-
window.onload=function hear()
{
var no=document.getElementsByTagName("ul")[0];
var msg="";
if (no.hasChildNodes())
{
var son=no.childNodes;
var i;
for (i=0;i<son.length;i++)
msg+=son[i].firstChild.nodeValue;
}
alert(msg);
}
任何帮助,将不胜感激。恭喜...
而不是childNodes
使用children
So,应该使用。
var son=no.children;
您的JS:
var son=no.children;
var i;
for (i=0;i<son.length;i++){
msg+=son[i].firstChild.nodeValue;
}
为什么不工作?
childNodes
还包括例如文本节点和注释。要跳过它们,请ParentNode.children
改用。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句