-1

我有一个场景在第一次或一次加载页面后刷新浏览器。因为页面加载时数据没有正确显示,当我刷新浏览器时它正在显示。我不知道原因。

非常感谢

4

2 回答 2

0

所以你只希望浏览器刷新一次?做这样的事情。

window.onload = function(){
    if(!document.location.hash){
        window.location = "#loaded";
    }
}

或jQuery

$(document).ready(function(){
    if(document.location.hash){
        window.location = "#loaded";
    }
});

但老实说,这只是一个临时解决方案。尽管你试图用快速修复来掩盖它。我保证它会回来困扰你。编写良好且结构化的代码将持续一生,并且始终可以在未来的项目中重用。

于 2011-08-10T15:31:53.467 回答
0

总是,您将不得不使用一些 JavaScript。您想要的是在页面完全加载时运行刷新代码。您可以使用 HTMLonload事件,但这样做存在问题(例如,它会在加载任何图像之前触发)。如果您想确保它在整个页面加载后触发,我建议您使用 JQuery 的ready()事件。

例子:

// NOTE: This will only work with JQuery loaded.
$(document).ready(function(){
    location.reload(true);
});

让它只在第一页加载时触发有点棘手。您可以向 URL 添加锚后缀以跟踪您是否已刷新页面,然后仅在 URL 中不存在时才刷新:

$(document).ready(function(){
    if(location.hash != "#")
    {
        // Set the URL to whatever it was plus "#".
        // (The page will NOT automatically reload.)
        location = "#";

        // Reload the page.
        location.reload(true);
    }
});

或者,您可以使用查询字符串,因为这会在更改时自动刷新页面:

$(document).ready(function(){
    var marker = 'r'; // 'r' is for "refreshed"
    if(location.search != "?"+marker)
    {
        // Set the URL to whatever it was plus "?r".
        // (This will automatically force a page reload.)
        location = "?"+marker;
    }
});

警告:对于这些示例中的任何一个,如果您的用户在将“#”或“?r”标签添加到 URL 之后为该页面添加书签,则当他们重新访问该页面时该页面不会刷新。如果您希望它是防弹的,您可能不得不使用 cookie 来代替。

于 2011-08-10T16:17:52.540 回答