更改URL后做些什么

After change URL do something

本文关键字:做些什么 URL 更改      更新时间:2023-09-26

我正在使用javascript加载我想要的路径,我想在更改url后执行一些代码。这是我的简单代码。

$(".addfr").click(function(){
    var pathname = window.location.pathname;
    if ((pathname == "/index.php") || (pathname == "/")) {
        $( "#tabbtn3" ).trigger( "click" );
        $('html, body').animate({
        scrollTop: $(".sideBaricons").offset().top
        }, 600);
    }
    else{
        window.location.href = '/index.php';
        $( "#tabbtn3" ).trigger( "click" );
        $('html, body').animate({
        scrollTop: $(".sideBaricons").offset().top
        }, 600);
    }
});

当我不在index.php时单击.addfr时,我重定向到index.php,然后我想关注特定的元素。但实际情况是,我的代码重定向并集中在我的前一个页面上,而不是在页面加载之后。

提前感谢您的帮助。

如果更改window.location.href,您将获得一个新的浏览器上下文(就像刷新一样)。此更改后,任何代码都无法执行。您的工作选项主要局限于将您想要的代码添加到您将用户重定向到的页面,或者使用一种相当复杂的称为History API 的东西

将URL设置为新页面会丢弃所有正在运行的代码。

一种选择:如果您希望代码保持存在(而不仅仅是更改浏览器URL),您可以将另一个页面的内容加载到当前页面中,例如使用Ajax调用。

注意:尽管需要这样做,但设计似乎出了很大的问题。最好说明页面的总体目标:)

您可以在重定向后传递参数,并在文档就绪设置的index.php页面中传递焦点

看看我的代码

$(function() {
    var url= window.location.href;
    if (url.indexOf('setFocus=true') > 0) {
        $("#tabbtn3").trigger("click");
        $('html, body').animate({
            scrollTop: $(".sideBaricons").offset().top
        }, 600);
    }
});
$(".addfr").click(function() {
    var pathname = window.location.pathname;
    if ((pathname == "/index.php") || (pathname == "/")) {
        $("#tabbtn3").trigger("click");
        $('html, body').animate({
            scrollTop: $(".sideBaricons").offset().top
        }, 600);
    } else {
        window.location.href = '/index.php?setFocus=true';
    }
});
相关文章: