Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
641 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 Reply

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');

});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...