Javascript 即使我将函数设置为仅在truthy时运行,仍然接收空错误?
我仍然收到此错误:Javascript 即使我将函数设置为仅在truthy时运行,仍然接收空错误?,javascript,google-chrome-extension,Javascript,Google Chrome Extension,我仍然收到此错误: Error in event handler: TypeError: Cannot set property 'innerHTML' of null 甚至在我将代码放入if(truthy){…}语句之后 chrome.runtime.onMessage.addListener(function(response, sender, sendResponse) { if(response) { console.log(response); document.
Error in event handler: TypeError: Cannot set property 'innerHTML' of null
甚至在我将代码放入if(truthy){…}语句之后
chrome.runtime.onMessage.addListener(function(response, sender, sendResponse) {
if(response) {
console.log(response);
document.getElementById('count').innerHTML = response;
}
})
我在这里遗漏了什么?这里是if语句应该包含的内容
if(document.getElementById('count') !== null) {..}
该错误意味着您的
getElementById()
调用返回null
,这意味着文档中没有具有该id的元素。感谢您的响应。是的,我知道这个错误意味着什么,但是我不明白为什么不能通过在应该调用代码的地方放置if(truthy){…}语句来解决这个问题。。元素最终返回一个实际值,但我试图绕过错误。您的if
语句检查response
的值,这显然与DOM中该元素的状态无关。您的代码没有检查getElementById()
是否返回非null。啊,我想我理解您的意思。谢谢你为我指出这一点。