2011-09-15 9 views
0

私はjQueryの初心者です。私はスクリプトを修正しようとしています。スクリプトのデモはhereです。今は、選択したタブの上に行を追加しますが、これは嫌です。私は何をしたいだけjQuery選択したタブにクラスを追加する

<a class="tab active" href="#">Tab Name</a> 

のようにアンカーに私はアクティブなボタンの背景色や何かを変更するためにCSSを使用することができ、そのようにクラスを追加しています。

以下のコードは、タブをクリックしたときの現在のコードです。

あなただけの必要
the_tabs.click(function(e){ 
    /* "this" points to the clicked tab hyperlink: */ 
    var element = $(this); 

    /* If it is currently active, return false and exit: */ 
    if(element.hasClass('.active')) return false; 

    $(this).addClass('active') 

答えて

2
the_tabs.click(function(e){ 
    var element = $(this); 
    if(element.hasClass('active')) { 
     return false; 
    } 
    else { 
     the_tabs.removeClass('active'); 
     element.addClass('active'); 
    } 
} 
+0

ありがとう!完璧に動作します。 – Drew

+0

あなたは歓迎します。あなたが時間を取ったときに答えてください:-) –

1

$(this).addClass('nameOfYourClass') 

クリックしたオブジェクト

+0

実際、私はそれを持っていると思う!それを一度クリックすると決して遠ざかりません。クリックして削除するにはどうすればよいですか?これまでのところで私のコードを更新しました。 – Drew

1

代わりの

if(element.find('.active').length) return false; 

if(element.hasClass('.active')) return false; 
0123を使用するクラスを追加しますあなたが見つけ、 .filter代わりの .findを使用する必要が

かは.activeクラスを持っている子ノードを検索しようとしているが、.filterフィルタアウトコレクションを照合CSS-selecotrを見つけるため

+0

ありがとうございます。クリックすればクラスを削除する関数はどこに置くのですか?今私の唯一の問題は、タブをクリックするとアクティブになりますが、次のタブをクリックするともう一方のタブがアクティブな状態になり、両方のタブがアクティブになります。そしてそれは続ける。 – Drew

+0

the_tabs.not(this).removeClass( ".active")はそれを行うべきですか? the_tabsがすべてあなたのタブの場合 – voigtan

0

はこのお試しください:

the_tabs.click(function(e){ 
    /* "this" points to the clicked tab hyperlink: */ 
    var element = $(this); 

    /* If it is currently active, return false and exit: */ 
    if(element.hasClass('active')) return false; 

    /* Detecting the color of the tab (it was added to the class attribute in the loop above): */ 
    var bg = element.attr('class').replace('tab ',''); 

    $('ul.tabContainer .active').removeClass('active'); 
    element.addClass('active'); 

    /* Checking whether the AJAX fetched page has been cached: */ 

    if(!element.data('cache')) 
    { 
     /* If no cache is present, show the gif preloader and run an AJAX request: */ 
     $('#contentHolder').html('<img src="img/ajax_preloader.gif" width="64" height="64" class="preloader" />'); 

     $.get(element.data('page'),function(msg){ 
      $('#contentHolder').html(msg); 

      /* After page was received, add it to the cache for the current hyperlink: */ 
      element.data('cache',msg); 
     }); 
    } 
    else $('#contentHolder').html(element.data('cache')); 

    e.preventDefault(); 
}) 

また、私のブログ(ウェブサイト)でいくつかの素晴らしいjQueryガイドを確認してください。 :)

関連する問題