最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - addEventListener() for DOMContentLoaded is not working - Stack Overflow

programmeradmin1浏览0评论

I have this code:

document.addEventListener('DOMContentLoaded', function() {
        hideColor();
 }, false);    

But, it doesn't seem to be binding the event listener to DOMContentLoaded. I have checked document.readyState and it says "loading". So, it means that DOMContentLoaded hasn't fired yet.

This is driving me crazy. Any ideas why it would not bind it?

I have this code:

document.addEventListener('DOMContentLoaded', function() {
        hideColor();
 }, false);    

But, it doesn't seem to be binding the event listener to DOMContentLoaded. I have checked document.readyState and it says "loading". So, it means that DOMContentLoaded hasn't fired yet.

This is driving me crazy. Any ideas why it would not bind it?

Share Improve this question edited Feb 23, 2021 at 12:26 Brian Tompsett - 汤莱恩 5,89372 gold badges61 silver badges133 bronze badges asked Mar 2, 2018 at 19:05 BlueboyeBlueboye 1,4944 gold badges27 silver badges54 bronze badges 3
  • Hive you tried just placing hideColor() before the </body> end tag? – zer00ne Commented Mar 2, 2018 at 19:07
  • 1 How do you load this script? Did you put it in <head>, at the end of <body> or is it loaded asynchronously? – zero298 Commented Mar 2, 2018 at 19:09
  • How is the page getting generated? Is it a static file or a dynamic script? It sounds like it is a script that is not closing the connection after sending the page, thus the perpetual "loading" state. – Useless Code Commented Mar 2, 2018 at 20:13
Add a ment  | 

1 Answer 1

Reset to default 3

This seems to works just fine...

function hideColor() {
    console.log("DOM fully loaded and parsed");
    console.log(document.readyState);
    var e = document.getElementById("test");
    e.style.background = "transparent";
  }
  
  document.addEventListener("DOMContentLoaded", hideColor);
#test {
  background:red;
}
<div id="test">Test</div>

发布评论

评论列表(0)

  1. 暂无评论