首页 > 解决方案 > setTimeOut 延迟从 html 中的 url 加载 href - 不工作

问题描述

href我在所有页面上都有一个链接,每次用户单击它时,我都想延迟从带有<a>标签的下一页加载。我试图<a>在 HTML 中的标记中获取链接,然后尝试延迟它,但超时不起作用。任何人都可以帮忙吗?

var link = document.querySelector('a').getAttribute('href')

setTimeout(function() {
  location.href = link
}, 4000);

标签: javascriptsettimeout

解决方案


我相信这会帮助你:

const a = document.querySelector('a');

a.addEventListener("click", (e) => {
  e.preventDefault();
  const link = e.target.href;

  setTimeout(() => {
    window.open(link)
  }, 1000)
})

jsfiddle 上的工作示例


推荐阅读