繁体   English   中英

我无法使用 document.getElementById 访问 html 元素?

[英]I can't access the html elements using document.getElementById?

当我尝试使用document.getElementById从我的 html 文件中获取我的元素时,我得到所有三个 const 变量的 null

以下是我的js文件的开头:

    const postBtn1 = document.getElementById("post-btn1");
    const postBtn2 = document.getElementById("post-btn2");
    const postBtn3 = document.getElementById("post-btn3");

以下是我的html文件的开头和包含按钮的部分:

<link rel="stylesheet" href="css/animate.css" />
<link rel="stylesheet" href="css/icomoon.css" />
<link rel="stylesheet" href="css/bootstrap.css" />
<link rel="stylesheet" href="css/superfish.css" />
<link rel="stylesheet" href="css/style.css" />
<script src="js/money-request.js"></script> <!-- this is the js file I'm using for this part -->
<script src="js/modernizr-2.6.2.min.js"></script>
</head>

JS 文件在加载后立即执行(在呈现 HTML 按钮之前。)

确保将按钮访问代码包装在 onload 块中:

window.onload = function() {
  const postBtn1 = document.getElementById("post-btn1");
  const postBtn2 = document.getElementById("post-btn2");
  const postBtn3 = document.getElementById("post-btn3");

  console.log(postBtn1);
};

这确保了 function 块内的代码仅在 html 页面完全呈现后执行,并且它们不再是 null。

要了解更多信息,请查看https://developer.mozilla.org/en-US/docs/Web/API/GlobalEventHandlers/onload

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM