[英]I can't access the html elements using document.getElementById?
When I am tryin to get my elements from my html file using document.getElementById
, I get null for all three const variables当我尝试使用document.getElementById
从我的 html 文件中获取我的元素时,我得到所有三个 const 变量的 null
The following is the beginning of my js file:以下是我的js文件的开头:
const postBtn1 = document.getElementById("post-btn1");
const postBtn2 = document.getElementById("post-btn2");
const postBtn3 = document.getElementById("post-btn3");
The following is the beginning of my html
file and section containing the buttons:以下是我的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>
The JS file is executed right away after it is loaded (Before the HTML buttons are rendered.) JS 文件在加载后立即执行(在呈现 HTML 按钮之前。)
Make sure you wrap your button access code inside an onload block:确保将按钮访问代码包装在 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);
};
This ensures the code inside the function block is only executed after the html page is fully rendered and they won't be null anymore.这确保了 function 块内的代码仅在 html 页面完全呈现后执行,并且它们不再是 null。
To learn more about this, check out https://developer.mozilla.org/en-US/docs/Web/API/GlobalEventHandlers/onload要了解更多信息,请查看https://developer.mozilla.org/en-US/docs/Web/API/GlobalEventHandlers/onload
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.