Refresh html loaded on div using jQuery?

两盒软妹~` 提交于 2019-12-11 20:33:45

问题


I am making a website and I use jQuery to load my html pages inside divs, so the main index html remains intact that way. The problem is that if a user is browsing an html that loads inside a div and tries to refresh his browser(F5) the content gets "lost" since it's only one page(index.html).

Is there a way to get around this?

<a onclick='$("#content").load("page1.html");'>Page1</a> 
<div id="content"></div>

回答1:


There's two solutions for that. If a user clicks a link, you add a hashtag to the url. For example:

<a onclick='$("#content").load("page1.html"); window.location.hash = "page1.html";'>Page1</a> 

Then, in your jQuery, you check for a hashtag when a user visits the site:

$(function() {
    if (window.location.hash.length) {
        var hash = window.location.hash.replace('#', '');

        $("#content").load(hash);
    }
});

Secondly, you could use cookies but I think the hash way works fine, too :)



来源:https://stackoverflow.com/questions/16686448/refresh-html-loaded-on-div-using-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!