Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
602 views
in Technique[技术] by (71.8m points)

jquery - Opening tab with anchor link

I have some typical tab content and I really need some help. I would like to achieve, that when user tries to get to a specific tab via external anchor link (http://www.url.com#content2), the navigation link becomes activated and the correct tab is shown.

Thank you for your help.

HTML

<nav class="inner-nav">
    <ul>
        <li><a href="#content1">Inner nav navigation link1</a></li>
        <li><a href="#content2">Inner nav navigation link2</a></li>
        <li><a href="#content3">Inner nav navigation link3</a></li>
    </ul>
</nav>

<section class="tab-content" id="content1">
    <article>
        content1 goes here
    </article>
</section>

<section class="tab-content" id="content2">
    <article>
        content2 goes here
    </article>
</section>

<section class="tab-content" id="content3">
    <article>
        content3 goes here
    </article>
</section>

JAVASCRIPT

$(document).ready(function () {
        $(".tab-content").hide();
    $(".tab-content:first").show();
    $(".inner-nav li:first").addClass("active");

    $(".inner-nav a").click(function(){
        $(".inner-nav li").removeClass("active");
        $(this).parent().addClass("active");
        var currentTab = $(this).attr("href");
        $(".tab-content").hide();
        $(currentTab).show();
        return false;
    });
});

I have a live example here So, if you click on the navigation, everything works ok, but if you want to go to a specific tab kajag.com/themes/book_your_travel/location.html#sports_and_nature the correct tab does not open.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You could solve this by simply checking the hash when the page loads, and then trigger a click on the right tab, like so:

$(function () {
    $(".tab-content").hide().first().show();
    $(".inner-nav li:first").addClass("active");

    $(".inner-nav a").on('click', function (e) {
        e.preventDefault();
        $(this).closest('li').addClass("active").siblings().removeClass("active");
        $($(this).attr('href')).show().siblings('.tab-content').hide();
    });

    var hash = $.trim( window.location.hash );

    if (hash) $('.inner-nav a[href$="'+hash+'"]').trigger('click');

});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...