Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/hibernate/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript getElementById()可以在html文件中工作,但不能在js文件中工作_Javascript_Html_Getelementbyid - Fatal编程技术网

Javascript getElementById()可以在html文件中工作,但不能在js文件中工作

Javascript getElementById()可以在html文件中工作,但不能在js文件中工作,javascript,html,getelementbyid,Javascript,Html,Getelementbyid,我在其他人的帖子中找不到我问题的答案,所以这里是: getElementById在java脚本文件中返回null(也在控制台中测试时),但在html文件中工作 HTML文件 <!DOCTYPE html> <html> <head> <title>Title</title> <link rel="stylesheet" href="css/style.css"> <script

我在其他人的帖子中找不到我问题的答案,所以这里是: getElementById在java脚本文件中返回null(也在控制台中测试时),但在html文件中工作

HTML文件

<!DOCTYPE html>
<html>
   <head>
      <title>Title</title>
      <link rel="stylesheet" href="css/style.css">
      <script src="js/app.js"></script>

   </head>
   <body>

      <p id="stuff">Some text</p>

   </body>
</html>

您可以像这样为文档事件
DOMContentLoaded
事件添加回调函数,并在该函数中执行所需的代码:

//Add this into your script file, and anything you want to have execute once the document
//is fully loaded go inside of the function
document.addEventListener("DOMContentLoaded", function(event) {
    var title = document.getElementById('stuff');
    console.log(title);
    title.style.color = "#D4F34A";
});

作为
的最后一个元素。因为当脚本运行时,DOM中还不存在该元素。或者添加事件侦听器来触发jsonready@zero298在之前将js文件链接到lat行是否正确?只有在脚本文件中的
DOMContentLoaded
事件触发后才能执行代码,文档()正在工作,谢谢@马蒂娜,不客气。如果您觉得这个答案是好的,请将其标记为已接受的答案。
//Add this into your script file, and anything you want to have execute once the document
//is fully loaded go inside of the function
document.addEventListener("DOMContentLoaded", function(event) {
    var title = document.getElementById('stuff');
    console.log(title);
    title.style.color = "#D4F34A";
});