Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/81.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 单击按钮,等待并重新加载页面_Javascript_Jquery - Fatal编程技术网

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节点对象