单击按钮,等待并重新加载页面

时间:2015-07-10 09:42:35

标签: javascript jquery

我正在寻找页面上的某些特定文本,然后在文本存在时自动单击按钮(否则在几秒钟后重新加载页面)。我想要的是在点击执行后重新加载页面(稍微延迟)。这是我的代码无效:

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秒后重新加载页面,并且点击不会被触发。我错过了什么吗?

3 个答案:

答案 0 :(得分:1)

使用.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);
}

说明:使用.click()绑定元素的点击事件。然后检查您的情况,如果满意,请使用.trigger()强制按钮单击。由于el是DOM节点,要将其转换为jquery对象,它必须由$()包装。

答案 1 :(得分:1)

假设我了解您要尝试实现的目标,您将在五秒钟后重定向,因为始终会进行setTimeout调用。您有一个if语句,但在两个块中都包含setTimeout。为什么呢?

setTimeout接受要评估的字符串或回调函数。在这种情况下,您的回调函数是window.location.reload - 您不需要将其包装在另一个匿名函数中。使用 -

setTimeout(window.location.reload, 5000);

代替。

所以你的简化代码是 -

if (hasText && el) {
    el.click();
    setTimeout(window.location.reload, 5000);
}

没有else阻止。

答案 2 :(得分:-1)

试试这个:

if (your condition = true) {
  setInterval(function() { 
    $(".btn.secondClass").trigger("click");
    window.location=""; 
  }, 5000);
}
      }