问题
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 :(
回答1:
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";
});
回答2:
This could be a possible duplicate Cannot read property 'addEventListener' of null but, try these solutions out, if your still having trouble explain more in detail.
来源:https://stackoverflow.com/questions/53575767/elementbyid-finds-element-but-wont-add-event-listener-chrome-extension