HTML link to trigger certain jQuery tabs

2019-09-15 09:49发布

After what seems like a very long time trying to find a solution, I thought it's about time to ask the experts.

I have implemented jQuery tabs to my site, however as well as selecting a tab to show the content, I would also like to be able to show the different tabs content if you click on a standard html link elsewhere on the page.

The page can be seen here http://www.luxury-spa-breaks.com/spa-deals-TEST.html and the html links in question are those down the left hand side (e.g. the user can either select the tab they want or select a region from the left hand side, which would then display that regions tab content).

This is the js I currently have:

$(document).ready(function() {

 //When page loads...
 $(".tab_content").hide(); //Hide all content
 $("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
  $(activeTab).fadeIn(2000); //Fade in the active ID content
  return false;
 });
});

You're help is massively appreciated!

Andy

1条回答
趁早两清
2楼-- · 2019-09-15 10:12

The easiest way to add the same functionality is to add the tabs class to the lefthand sidebar, or alternatively, add a selector that selects the sidebar menu to the selector for the tabs.

At this point I would suggest swapping out the code you have there for the one which I rewrote for another Stack Overflow question. It's more efficient and slightly cleaner by conforming to best practises.

var tabContents = $(".tab_content").hide(),
    tabs = $("ul.tabs li, .anynavbar ul li"); // Second selector to match left hand sidebar

tabs.first().addClass("active").show();
tabContents.first().show();

tabs.click(function() {
    var $this = $(this),
        activeTab = $this.find('a').attr('href');

    if(!$this.hasClass('active') && activeTab.length > 1 && activeTab.indexOf('#') === 0){
        $this.addClass('active').siblings().removeClass('active');
        tabContents.hide().filter(activeTab).fadeIn();
    }

    return false;
});

By doing either of the above, we can add the event handlers necessary to cause the tabs to change.

I've also edited the code to add in a simple check for valid href values for use with your HTML, where some of the anchors lack the correct corresponding href values to activate the correct tabs. Also, looking at the code you're using right now, you've missed out a }); at the end for the document.ready handler, which is why the code isn't working.

查看更多
登录 后发表回答