在页面加载而不是在链接点击时打开 javascript

时间:2021-06-10 14:00:02

标签: javascript onload

我有一个脚本,可以在单击任何链接时打开弹出窗口。如何更改此设置以在页面加载时打开弹出窗口。下面是脚本。

window.onload = function() {
  var puURL = 'http://www.example.com';
  var puTS = Math.round(+new Date()/1000);
  console.log('T.'+localStorage.puTS+'/'+puTS);
  if (typeof localStorage.puTS == 'undefined' || parseInt(localStorage.puTS) <= (puTS - 180)) {
    var links = document.getElementsByTagName('a');
    for(var i = 0, len = links.length; i < len; i++) {
      links[i].onclick = function (e) {
        var puHref = this.getAttribute("href");
          var puTarget = this.getAttribute("target");
          if (puHref !== '#' && puHref !== 'javascript:void(0)') {
          e.preventDefault();    
          if (puTarget == '_blank') {
            window.open(window.location.href);
          }
          window.open(puHref);
          window.location.href = puURL;
          localStorage.puTS = puTS;
        }
      }
    }
  }
};

1 个答案:

答案 0 :(得分:0)

好吧,目前您正在为所有目标元素添加点击处理程序:

for(var i = 0, len = links.length; i < len; i++) {
  links[i].onclick = function (e) { // <--- here
    var puHref = this.getAttribute("href");
    var puTarget = this.getAttribute("target");
    if (puHref !== '#' && puHref !== 'javascript:void(0)') {
      e.preventDefault();    
      if (puTarget == '_blank') {
        window.open(window.location.href);
      }
      window.open(puHref);
      window.location.href = puURL;
      localStorage.puTS = puTS;
    }
  }
}

如果您不想添加点击处理程序,而只想立即调用其中的逻辑,只需将该逻辑放入循环中,而无需点击处理程序:

for(var i = 0, len = links.length; i < len; i++) {
  var puHref = this.getAttribute("href");
  var puTarget = this.getAttribute("target");
  if (puHref !== '#' && puHref !== 'javascript:void(0)') {
    if (puTarget == '_blank') {
      window.open(window.location.href);
    }
    window.open(puHref);
    window.location.href = puURL;
    localStorage.puTS = puTS;
  }
}

当然,如果此逻辑包括打开新页面或重定向用户,那么这将在页面加载时立即发生...