简体   繁体   中英

Change URL with javascript

I have a tab system in HTML that uses the following javascript:

(function() {

        var $tabsNav    = $('.tabs-nav'),
            $tabsNavLis = $tabsNav.children('li'),
            $tabContent = $('.tab-content');

        $tabContent.hide();
        $tabsNavLis.first().addClass('active').show();
        $tabContent.first().show();

        $tabsNavLis.on('click', function(e) {
            var $this = $(this);

            $tabsNavLis.removeClass('active');
            $this.addClass('active');
            $tabContent.hide();

            $( $this.find('a').attr('href') ).fadeIn();

            e.preventDefault();
        });

    })();

The HTML Markup is:

<ul class="tabs-nav">

    <li class="active">
        <a href="#1">TAB 1</a>
    </li>
    <li>
        <a href="#2">TAB 2</a>
    </li>
    <li>
        <a href="#3">TAB 3</a>
    </li>

</ul><!-- end .tabs-nav -->

<div class="tabs-container">
    <div class="tab-content" id="1">

        CONTENT OF TAB 1

    </div><!-- end #tab1 -->

    <div class="tab-content" id="2">

        CONTENT OF TAB 2

    </div><!-- end #tab2 -->

    <div class="tab-content" id="3">

        CONTENT OF TAB 3

    </div><!-- end #tab3 -->

The UL are the names of the tabs, when you click one they take you to the content of that tab. As you can see when you click a tab the link is www.thepage.com#tab1 etc but in the adress bar doesnt appear anything. I want to be able to go to thepage.com#tab2 and to show the tab 2, but this isnt working.

I had searched different methods like window.location in javascript or pushstate in html5 posted in this page but I didnt know how to make them function. It will be best to use thepage.com/tab1 and not the hash tag for SEO purposes. I know you can achieve this with the pushstate in html5 like:

window.history.pushState(“object or string”, “Title”, “/new-url”);

If you use the pushstate html5 feature it won't work with IE8 and other older browsers, but if you just want to be able to have ajaxy-history you can use the hash portion of the url. You can modify the hash of the url by using:

window.location.hash="mytabid";
// url will be http://foo.com/#mytabid

Using this inconjuction with the hash change event (you'll probably want to use jQuery or a plugin to handle cross-browser event issues) you can react on the use of the back button or when the page loads by accessing the location.hash property.

window.onhashchange = function(a){
    console.log(a); //probably easiest to access the location.hash here.
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM