![](/img/trans.png)
[英]I can't get the value of <texterea /> using document.getElementById()
[英]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.