在IE浏览器中重新加载页面但不滚动到顶部

3
嗨,我有一个需要管理的大型项目表格。当我点击按钮时,我使用


$.post("update_the_database.php", { mode: 'themode', username: username },
            function(result){
                window.location.href = window.location.href;
        });

这将在后台运行"update_the_database.php",完成后重新加载页面。但它会回到页面顶部...

我尝试过:

window.location.href = window.location.href + '#the_id';

但在所有浏览器中(IE,Firefox,Chrome,Safari),它会更改地址栏中的URL但不重新加载页面。

从这里开始:

{{link1:window.location.href = window.location.href和window.location.reload()之间的区别}}

“如果URL中有锚点(#),则window.location.href = window.location.href不会重新加载页面- 在这种情况下,您必须使用window.location.reload()。”

所以我尝试了:

window.location.reload(true);

在Chrome和Safari中,当页面重新加载时会滚动到之前的位置,但在IE和Firefox中不会...

如何强制重新加载页面,即使URL中只更改了哈希值?

方法二:

window.location.hash = "#" + newhash;
window.location.reload(true);

现在它在Firefox中可以工作了... 顺便说一句,如果我在IE中使用window.location.reload(true);,它会出现:
Windows Internet Explorer

To display the webpage again, the web browser needs to
resend the information you've previously submitted.

If you were making a purchase, you should click Cancel to
avoid a duplicate transaction. Otherwise, click Retry to display
the webpage again.

Retry   Cancel   

你必须按下“重试”按钮,否则会出现一个错误页面,上面写着“网页已过期”。

为了避免IE弹出窗口,我目前正在执行以下操作:

                window.location.hash = "#<?php echo $id;?>";
                if (navigator.appName != 'Microsoft Internet Explorer') {
                    window.location.reload(true);
                }

尽管它只是将哈希放入地址栏,即使我转到地址栏并按回车键,它也不会刷新页面。我必须删除哈希并按回车键才能重新加载页面...(然后它会滚动到顶部)
3个回答

1

不要每次使用window.location.href附加'#id',这会导致问题,因为第二次附加时window.location.href已经包含一个id,而你又将另一个id附加到它上面。使用正则表达式'/^(.*)#/is'在window.location.href上查找重新加载之前的实际url。现在使用你编写的逻辑。

$.post("update_the_database.php", { mode: 'themode', username: username },
        function(result){
            var str = window.location.href;
            var patt1 = /^(.*)#/;
            window.location.href = patt1.exec(str)[1];
            window.location.href = window.location.href + '#the_id'
        }
}

window.location.href = window.location.href + '#the_id'; 尽管如此,它并不起作用(请参见编辑后的问题 - 它不会刷新页面,只会更改地址栏中的URL)。 - Luke Wenke

1

对于正则表达式的例子,我只能说:当你用正则表达式解决问题时,你知道他们会说什么!

    if(window.location.hash){
window.location.href = window.location.href.replace(window.location.hash,"#mynewhash");}

window.location.hash将包含URL中跟随“#”符号的部分,包括“#”符号。您可以监听hashchange事件以在支持的浏览器中获得关于哈希更改的通知。

支持的浏览器中,可以监听hashchange事件以获取有关哈希更改的通知。

请参见Mozilla文档


window.location.href = window.location.href + '#the_id'; 尽管如此,它并不起作用(请参见编辑后的问题 - 它不会刷新页面,只会更改地址栏中的URL)。 - Luke Wenke

1
我能想到的唯一的方法是保存由window.scrollY指示的滚动位置,并将其传递给下一个请求(例如:使用查询字符串)。然后,您可以创建一个代码来检查此键是否存在,并使用window.scrollTo(0, lastPos)跳转到该位置。如果您不使用任何JavaScript框架,则这并不美观且需要大量的代码(并且会弄脏您的查询字符串)。
如果您正在定期更新数据,则重新设计您的代码以进行ajax更新可能是值得的。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接