Change the URL in the browser without loading the new page using JavaScript

后端 未结 14 2491
忘掉有多难
忘掉有多难 2020-11-22 02:02

How would I have a JavaScript action that may have some effects on the current page but would also change the URL in the browser so if the user hits reload or bookmark, then

14条回答
  •  耶瑟儿~
    2020-11-22 02:36

    my code is:

    //change address bar
    function setLocation(curLoc){
        try {
            history.pushState(null, null, curLoc);
            return false;
        } catch(e) {}
            location.hash = '#' + curLoc;
    }
    

    and action:

    setLocation('http://example.com/your-url-here');
    

    and example

    $(document).ready(function(){
        $('nav li a').on('click', function(){
            if($(this).hasClass('active')) {
    
            } else {
                setLocation($(this).attr('href'));
            }
                return false;
        });
    });
    

    That's all :)

提交回复
热议问题