window.location.href无限循环

Aja*_*ery 2 javascript

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

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

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

Sco*_*ott 5

您正在创建自己的循环。

在您调用的页面启动时:

window.location.href = ("?name=" + new Date().getTime());
Run Code Online (Sandbox Code Playgroud)

这会导致页面自行加载并?name=time在末尾附加一个新内容。

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

window.document.location.hash = new Date().getTime();
Run Code Online (Sandbox Code Playgroud)

否则,您应该有条件地调用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
    }
}
Run Code Online (Sandbox Code Playgroud)