如何在 wordpress 页面内容完全加载后执行脚本
How can I execute script after wordpress page contents fully loaded
我正在为 wordpress post 页面制作一个插件,我正在尝试检测 ID 为“匹配”的 div。我可以使用浏览器工具看到 div,但是控制台会抛出消息指出 div 未找到。我认为那是因为脚本是在页面内容之前加载的。我怎样才能让它在 post 内容呈现后加载?
<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
函数中的元素。您必须将问题变量移动到函数中。
我正在为 wordpress post 页面制作一个插件,我正在尝试检测 ID 为“匹配”的 div。我可以使用浏览器工具看到 div,但是控制台会抛出消息指出 div 未找到。我认为那是因为脚本是在页面内容之前加载的。我怎样才能让它在 post 内容呈现后加载?
<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
函数中的元素。您必须将问题变量移动到函数中。