更改window.location.href时

时间:2018-02-23 10:44:23

标签: javascript jquery ajax

我试图在ajax成功时将页面滚动到底部时遇到问题。我正在设置window.location.href,因为我需要删除url中的哈希标记,然后我想将页面滚动到底部。但页面加载后页面仍然位于顶部。以下是我的代码。

我知道在ajax之外的页面重新加载后可以写入滚动到底部。但是这种滚动到底部的特殊要求并不是一直需要的,它基于一个按钮点击,其中写有ajax。

    $.ajax({
            url: updatedUrl,
            dataType: 'json',
            type: 'post',
            data: 'id=' +  id,
            complete: function() {},
            success: function(data) {
                window.location.href = window.location.href.split('#')[0];
                $('.overlay').hide();
                var $target = $('html,body'); 
                $target.animate({scrollTop: $target.height()}, 1000); 
            },
            error: function(xhr, ajaxOptions, thrownError) {
                alert(thrownError + "\r\n" + xhr.statusText + "\r\n" + xhr.responseText);
            }
    });

这可能是什么问题?如何删除哈希标记以及将页面滚动到底部?

2 个答案:

答案 0 :(得分:1)

执行window.location.href时 这将使用新的URL重新加载页面,此行旁边的行不会被取消。 如果您想在不加载页面的情况下更改网址,请替换window.location.href = window.location.href.split('#'[0];  与window.history.pushState("string", "Title", window.location.href.split('#')[0]);

这将更改URL而不重新加载

答案 1 :(得分:0)

我不知道那是否可能;当您加载另一个页面时,是另一个作用域,您无法从之前的页面脚本控制它。

但我有一些建议。

如果您可以更改“新页面”,请传递一些信息,例如URL中的查询字符串,并在新页面中包含一个脚本以进行scrollDown。

另一种选择:在IFRAME 100%中打开该页面。这样你就可以从“外部”进行控制(从“外部”执行代码有一些限制 - 它是相同的“原点”(同一个域)。

我看到你使用window.location.href = window.location.href.split('#')[0];。也许您可以在要滚动到底部时使用window.location.href = window.location.href.split('#')[0] + '#bottom';并在页面末尾添加<div id="bottom">

我希望有所帮助。

相关问题