简体   繁体   中英

ElementById finds element but won't add event listener (Chrome extension)

I have a form in my extension's popup with the code:

<button type="submit" id="update" class="btn btn-primary">Submit</button>

And then in the attached script, the following code:

document.addEventListener("DOMContentLoaded", function(event){
  var button = document.getElementById("update");
  button.addEventListener("click", test);
  button.style.color="red";
});



function test(){
  console.log("test");
}

The "button.style.color="red"" portion of the code works, so I know that the button was found successfully. However, I still receive this error upon load and when the button is clicked:

Uncaught TypeError: Cannot read property 'addEventListener' of null

How do I fix this :(

It is working in my demos, see: JSBin

    document.addEventListener("DOMContentLoaded", function(event){
     var button = document.getElementById("update");
     button.addEventListener("click", test);
     button.style.color="red"; 
    });

这可能是重复的无法读取null的属性'addEventListener',但是,如果您仍然无法详细解释,请尝试这些解决方案。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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