jQuery tabs - multiple sets on on page

爱⌒轻易说出口 提交于 2019-12-23 02:32:13

问题


This is kind of a follow on from a previous question I posted but I've not been able to get it to work..

I'm trying to use multiple sets of tabs (jQuery) on one page.

This is the code I had for one set of tabs which works great:

$('div.tabs div.tab').hide();
$('div.tabs div:first').show();
$('div.tabs ul.htabs li:first a').addClass('current');
$('div.tabs ul.htabs li a').click(function(){
    $('div.tabs ul.htabs li a').removeClass('current');
    $(this).addClass('current');
    var currentTab = $(this).attr('href');
    $('div.tabs div.tab').hide();
    $(currentTab).show();
    return false;
});

To use more than one set on the page I assigned #id's to each tab-set and tried to impliment this with:

$.each(['#tabs-1', '#tabs-2', '#tabs-3' ], function(id) {
    $(id + 'div.tab').hide();
    $(id + 'div:first').show();
    $(id + 'ul.htabs li:first a').addClass('current');
    $(id + 'ul.htabs li a').click(function(){
        $(id + 'ul.htabs li a').removeClass('current');
        $(this).addClass('current');
        var currentTab = $(this).attr('href');
        $(id + 'div.tab').hide();
        $(currentTab).show();
        return false;
    });
});

Obviously I'm doing something wrong here but as a jQuery newcomer I'm stumped!


回答1:


okay, so this was not working even with the correct spacing in the code but I have found a much more light-weight solution which works perfectly – jQuery MiniTabs:

/*
 * jQuery MiniTabs 0.1 - http://code.google.com/p/minitabs/
 */
jQuery.fn.minitabs = function(speed,effect) {
  var id = "#" + this.attr('id')
  $(id + ">div:gt(0)").hide();
  $(id + ">ul>li>a:first").addClass("current");
  $(id + ">ul>li>a").click(
    function(){
      $(id + ">ul>li>a").removeClass("current");
      $(this).addClass("current");
      $(this).blur();
      var re = /([_\-\w]+$)/i;
      var target = $('#' + re.exec(this.href)[1]);
      var old = $(id + ">div");
      switch (effect) {
        case 'fade':
          old.fadeOut(speed).fadeOut(speed);
          target.fadeIn(speed);
          break;
        case 'slide':
          old.slideUp(speed);  
          target.fadeOut(speed).fadeIn(speed);
          break;
        default : 
          old.hide(speed);
          target.show(speed)
      }
      return false;
    }
 );
}

Using this code you can then add:

$('#tabs-1').minitabs();
$('#tabs-2').minitabs();
$('#tabs-3').minitabs();

And everything works perfectly!




回答2:


$(id + 'div.tab').hide();

Isn't a space missing between the id and the 'div.tab' ? This would evaluate to "#tabs-1div.tab".



来源:https://stackoverflow.com/questions/2942563/jquery-tabs-multiple-sets-on-on-page

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!