Javascript window.location.href-刷新页面而不是重定向

Javascript window.location.href - Refreshes page instead of redirecting

本文关键字:重定向 window location href- 刷新 Javascript      更新时间:2023-09-26

我正在使用window.location.href重定向我的浏览器,我不知道为什么一个有效,另一个无效。当我使用相对链接时,它会刷新当前页面。当我使用完整的url时,它会重定向。我所在的页面和Process.aspx页面位于同一目录级别。所以我应该能够有一个相对的链接?不过,当我这样做的时候,它只是重新加载我所在的当前页面。关于window.location.href,我缺少什么基本想法?

    $(document).ready(function() {
    $( "button" )
        .button();
    $("#cancel")
        .click(function( event ) {
            alert("click");
            //Below Line Doesn't work
            window.location.href = "/Process.aspx";
            //Below Line Does work
            window.location.href = "http://localhost:65215/Process.aspx";
    });
});

在Mozilla开发者网络文档中,href是页面的整个URL。该列表中唯一的相对属性是path,它相对于页面的主机或域。

您可能还想看看使用reloadreplace方法。请参阅如何在JavaScript/jQuery中重定向到另一个网页?

这是一种边缘情况,但如果将事件侦听器添加到带有锚标记的容器div中,并且希望使每个容器div(而不仅仅是锚标记)都可以单击,然后重定向到锚标记的href attribute中包含的链接,也会出现此问题。在这种情况下,您希望包含event.preventDefault()以防止这种行为。

香草JS

document.getElementById("myAnchorDiv").addEventListener("click", function(event){
   event.preventDefault();
    //get url 
    URL = ...
   //Below Line should now work
   window.location.href = URL;
});

jQuery

$("#myAnchorDiv").on("click", function( event ) {
    event.preventDefault();
    //get url 
    URL = ...
    //Below Line should now work
    window.location.href = URL;
 });

如果您愿意,您当然可以将最后两行代码合并为一行代码,即类似window.location.href = [your URL];

的代码

尝试:location.href = location.origin + "/Process.aspx";

你可以尝试一个只刷新页面的破解,你可以实现onclick="location.href='wherever'",第二个href="/Process.aspx" onclick将首先被激发,href将带你回去。

试试这个:

window.location = window.location.protocol + 
                  '//' +
                  window.location.hostname +
                  window.location.pathname;