Javascript 单击按钮,等待并重新加载页面
我在页面上寻找一些特定的文本,如果文本存在,则自动单击按钮(否则几秒钟后重新加载页面)。我想要的是在执行单击后重新加载页面(稍微延迟)。以下是我的代码,它不起作用:Javascript 单击按钮,等待并重新加载页面,javascript,jquery,Javascript,Jquery,我在页面上寻找一些特定的文本,如果文本存在,则自动单击按钮(否则几秒钟后重新加载页面)。我想要的是在执行单击后重新加载页面(稍微延迟)。以下是我的代码,它不起作用: var content = document.body.textContent || document.body.innerText; var hasText = content.indexOf("this is my text")!==-1; el = document.querySelector(".btn.secondClas
var content = document.body.textContent || document.body.innerText;
var hasText = content.indexOf("this is my text")!==-1;
el = document.querySelector(".btn.secondClass");
if(hasText && el){
el.click()
{
setTimeout(function(){
window.location.reload()
},5000);
}
}
else {
setTimeout(function(){
window.location.reload()
},5000);
}
这似乎只是在5秒后重新加载页面,点击不会被触发。我遗漏了什么吗?使用
.trigger
方法强制单击。使用以下代码:
var content = document.body.textContent || document.body.innerText;
var hasText = content.indexOf("this is my text") !== -1;
el = document.querySelector(".btn.secondClass");
$(el).click(function() {
setTimeout(function() {
window.location.reload();
}, 5000);
});
if (hasText && el) {
$(el).trigger('click');
} else {
setTimeout(function() {
window.location.reload()
}, 5000);
}
说明:使用绑定元素的单击事件。单击()
。然后检查您的条件,如果满足,则使用.trigger()
强制按钮单击。由于el
是DOM节点,所以要将其转换为jquery对象,必须用$()
包装 试试这个:
if (your condition = true) {
setInterval(function() {
$(".btn.secondClass").trigger("click");
window.location="";
}, 5000);
}
}
假设我理解您试图实现的目标,您会在五秒钟后重新定向,因为
setTimeout
调用总是在进行。您有一个if
语句,但在两个块中都包含setTimeout
。为什么?
setTimeout
获取要计算的字符串或回调函数。在本例中,您的回调函数是window.location.reload
——您不需要将其包装在另一个匿名函数中。使用-
setTimeout(window.location.reload, 5000);
相反
所以你的简化代码是-
if (hasText && el) {
el.click();
setTimeout(window.location.reload, 5000);
}
没有
else
块。jquery标记的目的???您在单击中做什么没有trigger()
DOM节点方法,但是el
是一个DOM节点对象