0

我希望能够将更具描述性/有意义的 id 名称添加到 #tab0 到 #tab3 等以外的选项卡。对于此示例,我想以 URL 为目标的最后一个选项卡http://domainName/tagetpage/#services。请记住,我宁愿不使用 jQuery UI 选项卡。此脚本允许我为特定选项卡添加书签或从另一个页面链接到特定选项卡。谢谢

这是我的代码:

jQuery(document).ready(function(){


    $('#tabs').append('<ul id="tabs"></ul>')
    $('.tabs').each(function(i){
        // Gives element a unique ID -
        this.id = 'tab'+i;
        // If a title does not exist then use the ID for anchor text -
        var title = (this.title) ? this.title : this.id;
        // Define contents of link (to go within list items) -
        var link = '<a href="#' + this.id + '">' + title + '</a>';
        // Append list items to UL -
        $('<li>'+link+'</li>').appendTo('#tabs ul');

        // Check if the URL contains an anchor
        var url = document.location.toString();
        if (url.match('#')) {
            // Get the name of the anchor used in the URL
            var anc = '#' + url.split('#')[1];
            // Hide all TABS -
            $('.tabs').hide();
            // Show the corresponding content
            $(anc).show();      
        } else {
            // Hide all Tabs except the first one -
            if(i===0) $('.tabs:not(#'+this.id+')').hide();
    }
    if (url.match('#')) {       

        // Get the name of the anchor used in the URL    
        var anc = '#' + url.split('#')[1];
        $('#tabs a[href='+anc+']').addClass("active"); }// < ADD THIS LINE
    })

    $('#tabs a').click(function(){

        // get ID of tab to be shown -
        var id = '#'+this.href.split('#')[1];
        // Hide all TABS -
        $('.tabs').hide();
        // Show the tab which matches anchor's href -
        $(id).show();
        $('a').removeClass("active");
        $(this).addClass("active");
        // Don't forget to return false -
        //return false;
    })
   });

HTML

 <section>

 <div class="tablist">
 <div id="tabs"></div>
 </div>


 <div class="tabs" title="Tab 1 title">
<p>content for tab 0</p>
 </div>

 <div class="tabs" title="Tab 2 title">
<p>content for tab 1</p>
 </div>

 <div class="tabs" title="Tab 2 title">
<p>Some cool content for the third tab</p>
 </div>
 <div class="tabs" title="Services">
 <h2>Tab 4 </h2>
 <p>content for tab 3</p>
 </div>
</section>
4

2 回答 2

0

然后使用该title属性设置 ID。但要小心,所有titles 都应该是唯一的。

this.id = this.title ? this.title.toLowerCase().replace(/\s+/g, "_") : 'tab' + i;

它将tab_2_titleTab 2 title和。services_Services

于 2012-05-13T11:19:17.870 回答
0

我仍然认为对于唯一 ID,您可以使用元素位置:这是VisioNs answer + i

this.id = this.title ? this.title.toLowerCase().replace(/\s+/g, "_") + '_' + i : 'tab' + i;
于 2012-05-13T13:43:24.200 回答