网站上有一个"立即预订"选项卡。 当您单击它时,它会打开一个表单。如果 URL www.example.com/en/?emailer
,我需要使按钮自动打开。我试过这个:
if (window.location.href == "http://www.example/en/?emailer") {
document.getElementsByClassName("tab")[0].click();
}
问题是,如果我将此代码粘贴到控制台的页面上,它就可以工作。但是,当我将其添加到标题.php WordPress文件时,它不起作用。
知道为什么它在控制台中而不是在<head>
中工作吗?有人可以告诉我如何完成此操作吗?
注意:该选项卡具有类"选项卡",如代码部分所示。
试试这个
jQuery(document).ready(function( $ ) {
if (window.location.href == "http://www.example/en/?emailer") {
document.getElementsByClassName("tab")[0].click();
}
});
你应该为此使用 onreadystatechange
$(document).on('readystatechange', function() {
if (window.location.href == "http://www.example/en/?emailer") {
document.getElementsByClassName("tab")[0].click();
}
});
事实上,问题在于,在执行脚本时,DOM 树尚未完全构建。快速修复将是一个简单的
setTimeout(function () {
if (window.location.href == "http://www.example/en/?emailer") {
document.getElementsByClassName("tab")[0].click();
}
}, 0);
像这样,您等待事件循环中的下一个刻度,即设置 DOM 树时。