2012-12-18 160 views
2

我正在使用jQuery选项卡的实现和一切工作很好,但我想能够链接到一个URL例如http://www.mydomain.com/tabs.html#tab2并让页面自动打开选项卡2,继承人我在迄今为止其中http://jsfiddle.net/Jmx7k/jQuery选项卡 - 直接转到特定的选项卡从URL

<script> 
jQuery(document).ready(function() { 
    jQuery('#tabs2 li a:not(:first)').addClass('inactive'); 
    jQuery('.container:not(:first)').hide(); 

    jQuery('#tabs2 li a').click(function() { 
     var t = jQuery(this).attr('href'); 
     if (jQuery(this).hasClass('inactive')) { //added to not animate when active 
      jQuery('#tabs2 li a').addClass('inactive'); 
      jQuery(this).removeClass('inactive'); 
      jQuery('.container').hide(); 
      jQuery(t).fadeIn('slow'); 
     } 
    return false; 
}) //end click 
});​ 
</script> 
    <div id="tabs2holder"> 
     <ul id="tabs2"> 
     <li><a href="#tab1">Test Tab 1</a></li> 
     <li><a href="#tab2">Test Tab 2</a></li> 
    </ul> 
</div> 

<div class="container" id="tab1"> 
    This is test content for tab1 
</div> 


<div class="container" id="tab2"> 
    This is test content for tab2 
</div> 

有人能指出我在添加此功能的正确方向,也解释了为什么目前并没有这样做呢?

感谢

+2

你知道吗,你只需要以长格式编写'jQuery'一次?通过将代码封装在'(function($){....})(jQuery);'中,无论是否使用了noConflict,都可以使用'$'。 – ThiefMaster

+1

也许你可以使用这个:http://benalman.com/projects/jquery-bbq-plugin/ – Joonas

回答

4

好吧,如果你想创建一个哈希一部分(例如“#TAB2”)的网址,你可以用

var hash = location.hash; // hash = '#tab2' 

变化得到这个值你这样的代码

jQuery(document).ready(function() { 
    jQuery('#tabs2 li a:not(:first)').addClass('inactive'); 
    jQuery('.container:not(:first)').hide(); 

    jQuery('#tabs2 li a').click(function() { 
     var t = jQuery(this).attr('href'); 
     if (jQuery(this).hasClass('inactive')) { //added to not animate when active 
      jQuery('#tabs2 li a').addClass('inactive'); 
      jQuery(this).removeClass('inactive'); 
      jQuery('.container').hide(); 
      jQuery(t).fadeIn('slow'); 
     } 
     return false; 
    }); //end click 

    if (location.hash == '#tab2') { 
     // don't forget to put id-attributes to your li-elements 
     jQuery('#tablink2 a').trigger('click'); 
    } 
});​ 

另请参见:http://jsfiddle.net/Jmx7k/8/ by jsfiddle散列属性不会影响javascript区域:-(在正常情况下尝试它。

相关问题