我正在制作一个wordpress帖子页面插件,我试图检测div与id "matched"。我可以用浏览器工具看到div,但是控制台会抛出没有找到div的消息。我认为这是因为脚本在页面内容之前加载。我怎样才能使它加载后的帖子内容已经渲染?
<script type="text/javascript">
var question = document.getElementById("matched");
window.onload = function afterWebPageLoad() {
if(question){
console.log("id 'matched' exists");
} else {
console.log("id 'matched' not found");
}
}
</script>
在等待onload
侦听器加载页面之前,您正在调用document.getElementById
将变量声明移动到onload
监听器内部,这样它只在页面加载时被调用。
你的代码应该是什么样子:
<script type="text/javascript">
window.onload = function afterWebPageLoad() {
var question = document.getElementById("matched"); // <-- Moved inside
if (question) {
console.log("id 'matched' exists");
} else {
console.log("id 'matched' not found");
}
}
</script>
<p id="matched">match element</p>
您可以这样使用setInterval
;
let checker = setInterval(function () {
if (document.getElementById("matched") !== null) {
console.log("found")
clearInterval(checker)
} else {
console.log("checking..")
}
}, 100)
另外,您必须检查afterWebPageLoad
函数中的元素。你必须把问题变量移到函数中。