0

このコードでメニューにタブを付けました:

$('#menu').each(function(){
    // For each set of tabs, we want to keep track of
    // which tab is active and it's associated content
    var $active, $content, $links = $(this).find('a');

    // Use the first link as the initial active tab
    $active = $links.first().addClass('active');
    $content = $($active.attr('href'));

    // Hide the remaining content
    $links.not(':first').each(function () {
        $($(this).attr('href')).hide();
        $("#tab1").show();
    });

    // Bind the click event handler
    $(this).on('click', 'a', function(e){
        // Make the old tab inactive.
        $active.removeClass('active');
        $content.hide();

        // Update the variables with the new link and content
        $active = $(this);
        $content = $($(this).attr('href'));

        // Make the tab active.
        $active.addClass('active');
        $content.show();

        // Prevent the anchor's default click action
        e.preventDefault();

    });
});

問題は、タブへの直接リンク (site.com/#tab2 など) に関するもので、機能しません。この問題を解決する方法はありますか?

4

2 に答える 2

1

これをチェックして....

実施例

Jquery に追加する

$(document).ready(function(){
var x = $(location).attr('href').replace( 'http://yourdomain.com/yourpage.html' , "");
$('a[href="' + x + '"]').click();
});
于 2012-11-05T04:06:47.233 に答える
0

各タブに固有のid属性を与えます。例えば:

<div id="menu">
   <div id="tab1">...</div>
   <div id="tab2">...</div>
   ...
</div>

タブのIDを指定して、タブを表示するための一般的な関数を作成します。

function showTab(tabId) {

    // find the requested tab using the given id
    var tab = $(tabId);

    // Make the old tab inactive.
    $active.removeClass('active');
    $content.hide();

    // Update the variables with the new link and content

    $active = tab;
    $content = $(tab.attr('href'));

    // Make the tab active.
    $active.addClass('active');
    $content.show();

    // Prevent the anchor's default click action
    e.preventDefault();
}

イベントを使用してhashchange、ハッシュが変更されるたびに適切なタブを表示します。

$(window).on('hashchange', function() { 
    showTab(location.href);
});

showTab メソッドも使用するようにクリック ハンドラーを書き直します。

$(this).on('click', 'a', function(e){
    showTab($(this).attr('id'));
});

ページが最初に読み込まれるときに、適切なタブを選択します。

$(document).ready(function() {
    showTab(location.href);
});
于 2012-11-05T03:48:45.653 に答える