首页 > 解决方案 > 如何在调用 window.location.href 后运行函数?

问题描述

我正在尝试重定向到另一个站点,然后在其上运行代码。

function gotonewpage() {
  window.location.href = "WEBSITE"
  x = document.getElementById("s")
}

标签: javascripthtml

解决方案


好吧,window.location.href 重新加载了应用程序,其余代码永远没有机会执行它。

这就像在函数中的 return 关键字之后使用语句。

function sum(a, b) {
   var sum;
   return sum;

   sum = a + b; // this will never execute
}

但是你能做什么,重定向发生后,你可以添加这个

x = document.getElementById("s")

在发生重定向的文件中。但是恐怕您也必须在新文件中添加带有 id 's' 的元素。


推荐阅读