开发者

jquery add on page load show requested tab feature

开发者 https://www.devze.com 2023-02-22 18:14 出处:网络
I\'m a newbie with jquery and i\'ve used this code for tabs <script type=\"text/javascript\" charset=\"utf-8\">

I'm a newbie with jquery and i've used this code for tabs

<script type="text/javascript" charset="utf-8">
    $(function () {
        var tabContainers = $('div.tabs > div');
        tabContainers.hide().filter(':first').show();

        $('div.tabs ul.tabNavigation a').click(function () {
            tabContainers.hide();
            tabContainers.filter(this.hash).show();
            $('div.tabs ul.tabNavigation a').removeClass('selected');
            $(this).addClass('selected');
            return false;
  开发者_如何学Python      }).filter(':first').click();
    });


</script>

What i need is to be able to load a specific tab when open a url like: www.mysite.com/page.html#tab1

html link looks like this:

<a href="#tab1" class="selected">name link</a>
<a href="#tab2" class="">name link2</a>
<a href="#tab3" class="">name link3</a>

I've tryied lots of scripts, but maybe is my fault (i'm a dude with javascript)

Thank you in advance


JQuery-UI have a tab-widget You can use.

Much simpler and more stable than writing your own.

For different URL's please have a look at this post.

It tells you how to leverage on the UI-themes and load different URl's.

Otherwise You have to do a $('#theIdOfTheDiv').load(url) on the click event in the tab


  1. You need an anchor like <a href="#tab1">click to see tab1</a>

  2. You need to redirect the user to #tab1 so you have to remove the return false; line of your function wich disables the redirecting

  3. Your function is being triggered when the <a> is clicked, you need to trigger it once more when the page is being loaded

your function will look like this

$(function(){
    onClickHandler = function() {
      $('div.tabs > div').hide();
      $(window.location.hash).show();
    }
    $('div.tabs ul.tabNavigation a').click(onClickHandler);
    onClickHandler();
});


The tab you want displayed by default should have a class of selected in your HTML. So should the associated content wrapper. The others should not.


window.location has a hash attribute. So, you can check it against the empty string and if it's not empty, select that tab:

if(!window.location.hash === "")
    $(window.location.hash).show();
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号