2012-05-13 1 views
0

#tab0〜#tab3以外のタブに、わかりやすい/意味のあるID名を追加したいと考えています。この例では、 URLがhttp://domainName/tagetpage/#servicesの最後のタブをターゲットに設定します。私はむしろjQueryのUIタブを使用したくないことに気をつけてください。このスクリプトを使用すると、特定のタブまたは別のページの特定のタブへのリンクをブックマークすることができます。おかげもっとわかりやすい/意味のあるID名をタブに追加する

ここでは私のコードです:

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> 
+1

そして質問があります? –

+0

あなたは次のような意味ですか? 'var title =(this.title)? this.title:$(this).attr( 'title'); '?私はquesitonを理解しているか分からない。 – ubik

+0

私は「domaneName/tagetPage /#tab3」を取得しています。「... targetPage /#services」を取得したいと思います。申し訳ありませんが、質問が明確でない場合は – NickP

答えて

0

は、IDを設定するtitle属性を使用します。しかし、すべてtitleは一意でなければなりません。

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

それはServicesためTab 2 titleためtab_2_titleservicesを行います。

+0

VisioN;それはうまくいった! – NickP

+0

VisioN - このスクリプト例でアンカーにリンクする方法link to anchorになります。 – NickP

+0

単に '...'を使うか、何が問題なのですか? :) – VisioN

0

ユニークあなたは要素の位置を使用することができますIDSのため、私はまだだと思う: それは、ビジョン答えです+ I

this.id = this.title ? this.title.toLowerCase().replace(/\s+/g, "_") + '_' + i : 'tab' + i; 
関連する問題