<html>
<head>
<script type="text/javascript" src="jQuery.js">
<script type="text/javascript">
x=document.getElementByTagName("p");
document.write(x.lastChild.nodeValue);
</script>
</head>
<body>
<p id="intro">Hello World 1!</p>
<p id="intro">Hello World 2!</p>
<p id="intro">Hello World 3!</p>
</body>
</html>
为什么上面的代码不起作用。我想通过使用语句 documetn.write(x.lastChild.nodeValue()); 来显示 [Hello World 3!] 提前致谢...
最佳答案
您的代码中有几个错误:
- 您在 HTML 加载完成之前执行 JavaScript。因此
<p>
当您想要查询它们时它们不存在。
简单的解决方案是移动您的 <script>
标记到 HTML 页面底部。
- 命令是
document.getElementsByTagName()
(而不是document.getElementById()
- 请注意添加的“s”)并返回一个数组。
所以这里正确的语法是这样的:
x = document.getElementsByTagName("p");
x = x[ x.length - 1 ];
- 为什么要使用
document.write()
?这将在脚本标记的位置插入文本。
因此,为了调试,最好使用 console.log()
或alert()
。在生产环境中,您将得到结果 - <div>
例如。
所以最后你的代码可能看起来像这样才能工作:
<html>
<head>
<script type="text/javascript" src="jQuery.js">
</head>
<body>
<p id="intro">Hello World 1!</p>
<p id="intro">Hello World 2!</p>
<p id="intro">Hello World 3!</p>
<hr>
<div id="result"></div>
<script type="text/javascript">
x=document.getElementsByTagName("p");
x = x[ x.length - 1 ];
document.getElementById( 'result' ).innerHTML = x.nodeValue;
</script>
</body>
</html>
关于javascript - x.lastChild.nodeValue,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11222930/