javascript - x.lastChild.nodeValue

标签 javascript html

<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/

相关文章:

javascript - 使用javascript强制IE9进入兼容模式

javascript - 无法更改 Bootstrap 5 toast 上的选项

javascript - 如何从提到的字符串中获取逗号分隔的值

javascript - 如何根据图片点击打开局部 View ?

javascript - Dblclick 事件处理程序不响应苹果设备

javascript - jQuery UI Sortable Widget动态添加列表不触发事件

css - DIV 像表格一样对齐

html - 图像上的文本和背景颜色叠加

html - CSS 没有正确格式化我的消息

javascript - 检查ajax/php返回的数据