jquery javascript: adding browser history back with hashtag?

左心房为你撑大大i 提交于 2019-11-28 11:35:46

A great resource and plugin to help with this is Ben Almans bbq plugin, It will help you set and read the hash part of the url (eg see pushState and getState) and it provides a hashchange event that works across browsers.

Handle the hashchange event and do your processing in there. You need to manually trigger the event the first time the page loads.

$(document).ready(function(){

    $(window).bind( 'hashchange', function( event ) {

        // show/hide map here. this will vary depending on what you use in the url

        if (window.location.hash == "map"){
            $('#mapContainer').fadeIn('fast', function () {
               loadMap("mapContainer");
            });
        } else {
            $('#mapContainer').fadeOut('fast', function () {
                $(this).children().remove();
            })
        }

    });

    $('.showMapLink').live('click', function() {
        top.location.hash = "map";
    });

    $(window).trigger("hashchange");

});
Fortega

Probably, half of your question is answered here: jQuery removing hash value from URL

Yes, it's possible (with recentish) browsers.

See document.location.hash to add #map to the current URL.

Register an onhashchange event listener to look for changes, but note that when you set the tag, it also raises such an event. Hence you need to discard any event which contains the same hash as the one you just set.

Alternatively, look at the jQuery history plugin, which has workarounds for older browsers.

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