0

当我通过 url:www.domain.com/#ratings 时,评级选项卡应该打开,现在它在 url 中显示当前选项卡,但不适用于链接选项卡

<script type="text/javascript">
    $(document).ready(function () {
        $('.tabs a').click(function () {
            switch_tabs($(this));
        });
        switch_tabs($('.defaulttab'));
    });

    function switch_tabs(obj) {
        $('.tab-content').hide();
        $('.tabs a').removeClass("selected");
        var id = obj.attr("rel");
        $('#' + id).show();
        obj.addClass("selected");
    }
</script>
<ul class="tabs">
    <li>
        <a href="#movies" class="defaulttab" rel="movies">Tutorial</a>
    </li>
    <li>
        <a href="#ratings" rel="ratings">Comments</a>
    </li>
</ul>
<div class="contentbox">
    <div class="tab-content" id="movies">movie tab</div>
    <div class="tab-content" id="ratings">rating tab</div>
</div>
4

3 回答 3

1

你有没有试过这个:

$(function(){
  var hash = window.location.href.split('#').pop();
  var allowed = ['hello', 'world'];
  if(allowed.indexOf(hash) == -1) hash = allowed[0];
  switch_tabs($('a[href=#'+hash+']'));
});
于 2012-06-05T06:44:14.483 回答
1

试试这个,

 $(document).ready(function () {
        $('.tabs a').click(function () {
            var $this = $(this);
            $('.tabs a').removeClass("selected");
            $this.addClass('selected');
            switch_tabs($this.attr('href'));
            return false;
        });
        var anchor;
        var hash = $('a[href="' + location.hash + '"]');
        if(hash.length > 0){
            anchor = hash;
        }
        else{
            anchor = $('.defaulttab');
        }
        anchor.click();
    });

    function switch_tabs(hash) {
        $('.tab-content').hide(); 
        $(hash).show();   
        location.hash = hash;
    }
于 2012-06-05T07:03:27.443 回答
0

使用 switch_tabs(window.location.hash); ?

例如:

    $(window).bind('hashchange', function() {
    alert(window.location.hash.split('#').pop());
        switch_tabs(window.location.hash);
    });

当哈希更改调用您的函数时

于 2012-06-05T06:49:57.583 回答