Window.location.href infinite loop

Window.location.href infinite loop

本文关键字:loop infinite href location Window      更新时间:2023-09-26

使用 window.location.href 时,我遇到了无限循环(即使它被放置在启动期间只调用一次的函数中)。

function onYouTubeIframeAPIReady() { // only called one time once API's are ready
        window.location.href = ("?name=" + new Date().getTime()); //is EPOCH time

window.location.hash工作得很好(但我不能使用它)...

您正在创建自己的循环。

在启动您正在调用的页面时:

window.location.href = ("?name=" + new Date().getTime());

这会导致页面加载自身,并在末尾附加一个新?name=time

您可能想要做的是更改 URL 的哈希部分。 这样:

window.document.location.hash = new Date().getTime();

否则,您应该有条件地调用window.location.href以便它仅在特定时间执行,如下所示:

function onYouTubeIframeAPIReady() { // only called one time once API's are ready
    if (someVariable == "refreshNow") {
          window.location.href = ("?name=" + new Date().getTime()); //is EPOCH time
    }
}

如果此函数在启动期间运行,并且没有任何条件可以阻止它运行,则每次都会执行window.location.href部分,从而导致您描述的循环。 您需要提供一些条件来停止循环。