开发者

Add an active class to li element if link has a hash tag, then make li element active

开发者 https://www.devze.com 2023-02-27 09:56 出处:网络
I\'m new to working with jQuery tabs, and I want to be able to add the functionality of linking directly to a specific tab from outside. Basically everything is working just fine the tab content shows

I'm new to working with jQuery tabs, and I want to be able to add the functionality of linking directly to a specific tab from outside. Basically everything is working just fine the tab content shows up but the actual tab does not activate, however开发者_JAVA技巧 when you click it, it shows up. I have background images set for the tabs. This is what my css looks like

ul.tabs li a.tab-1 {background-position:0 0;}
ul.tabs li a.tab-1:hover {background-position:0 -61px;}
ul.tabs li.active a.tab-1 {background-position:0 -125px;}

The active class does not show when you are sent to the link from an outside source.

<ul class="tabs">
  <li class="active"><a class="tab-1" href="#tab-1">history</a></li>
  <li><a class="tab-2" href="#tab-2">About</a></li>
</ul>

Here is rest of jQuery code:

$(document).ready(function() {
  //Default Action
  $(".tab_content").hide(); //Hide all content
  if(location.hash != "") {
    /* If there is a tab id in the page URL */
    $(location.hash).show(); //Show tab content
    $('ul.tabs li:has(a[href="location.hash"])').addClass("active").show(); //Activate tab
    $(this).find("a").addClass("active"); //Add "active” class to href inside selected 
  } else {
    $("ul.tabs li:first").addClass("active").show(); //Activate first tab
    $(".tab_content:first").show(); //Show first tab content
  }
  //On Click Event
  $("ul.tabs li").click(function() {
    $("ul.tabs li").removeClass("active"); //Remove any "active" class
    $(this).addClass("active"); //Add "active" class to selected tab
    $(".tab_content").hide(); //Hide all tab content
    var activeTab = $(this).find("a").attr("href"); //Find the href attribute value to identify the active tab content
    location.hash = activeTab //Add the anchor to the url (for refresh)
    $(activeTab).fadeIn(); //Fade in the active ID content
    return false;
  });
});

What I'm trying to achieve is if the url has a specific location: ../../#tab-1 set the li to active and show the active state for the li element.


You can simulate a click event:

$(document).ready(function() {
  //create tab widget before the following code is executed
  $(".tab_content").hide(); //Hide all content
  if(location.hash != "") {
    $(location.hash).show(); //Show tab content
    $('ul.tabs li:has(a[href="'+location.hash+'"])').click(); //LINE CHANGED
  } else {
    $("ul.tabs li:first").click(); //LINE CHANGED
  }
... your code continues here

Also, you had an error inside your has (you forgot to concat location.hach variable) Hope this helps

0

精彩评论

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