[英]How to fix Uncaught TypeError: Cannot set property 'innerHTML' of null in javascript in wordpress?
const printSentence = (id, sentence, speed = 50) => { let index = 0; let element = document.getElementById(id); let timer = setInterval(function() { const char = sentence[index]; if (char === '<') { index = sentence.indexOf('>', index); // skip to greater-than } element.innerHTML = sentence.slice(0, index); if (++index === sentence.length) { clearInterval(timer); } }, speed); } // printSentence printSentence( 'one', '<h2>Wordpress</h2>', 50 );
<div id="one"></div>
But I see an error in console:但是我在控制台中看到一个错误:
Uncaught TypeError: Cannot set property 'innerHTML' of null
未捕获的类型错误:无法设置 null 的属性“innerHTML”
I tried window.onload
but it doesn't work我试过
window.onload
但它不起作用
Any tip of how to fix this problem in console?有关如何在控制台中解决此问题的任何提示?
This means that let element = document.getElementById(id);
这意味着
let element = document.getElementById(id);
is returning null.正在返回空值。 (Add a console.log of element, to check, if you like).
(添加元素的 console.log 以进行检查,如果您愿意的话)。
Most likely reason for this is that there is no tag with id "one".最可能的原因是没有 id 为“one”的标签。
Make sure that it has a tag with id "one".确保它有一个 ID 为“one”的标签。 The commonest reason for getting into this situation is that the DOM doesn't contain the element with id "one" at the time the javascript is running.
出现这种情况的最常见原因是 DOM 不包含在 JavaScript 运行时 ID 为“one”的元素。
That is why it is best to use the这就是为什么最好使用
icon to enter your code so that it can be replicated easily by others.
图标输入您的代码,以便其他人可以轻松复制。
It is showing a slowly-appearing text in the output window.它在输出窗口中显示缓慢出现的文本。 In the console log, I am seeing an irrelevant error message, perhaps something to with security.
在控制台日志中,我看到一条不相关的错误消息,可能与安全有关。
Uncaught DOMException: Blocked a frame with origin "null" from accessing a cross-origin frame.
at Object.vAPI.bootstrap (chrome-extension://cjpalhdlnbpafiamejdnhcphjbkeiagm/js/contentscript.js:1755:46)
at chrome-extension://cjpalhdlnbpafiamejdnhcphjbkeiagm/js/contentscript.js:1764:6
If it is working for you too, but you are concerned about your error message that you described, why don't you do this:如果是为你工作太多,但你关心你的错误信息,你所描述的,你为什么不这样做:
Change改变
element.innerHTML = sentence.slice(0, index);
to到
if(element){
element.innerHTML = sentence.slice(0, index);
} else {
console.log("Cannot do element.innerHTML. The current value of element is ",element,". Index is currently ",index)
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.