2016-03-24 14 views
0

私はGoogleとこのフォーラムで調べましたが、必要なものが見つからないか、コードに適用する方法がわかりません。タブがアクティブなときに子(孫)クラスを変更する

私が達成しようとするのは、タブが選択されているときにアイコンを変更することです(強調表示します)。アイコンのために私はスプライトimgを使用し、{{icon}}はアイコンの名前を持つリストです。

HTML:

<ul class="nav nav-icons" role ="tablist"> 
    {% for icon in icon_list1 %} 
    <li class="nav-item"> 
    <a href="#{{icon}}" role="tab" aria-controls="{{icon}}" data-toggle="pill" aria-expanded="false"> 
     <div class="icon-{{icon}}"></div> 
    </a> 
    </li> 
    {% endfor %} 
</ul> 
  • は、私は別のセクションごとに異なるicon_listと私のページにこのコードを3回を持っています。 とページがアクティブになるように、各リストでの最初の項目をロードし、ので、ここでのliのelemがアクティブdiv要素があるとき(赤色のアイコン)

JS

$(document).ready(function() { 
    $('.nav.nav-icons .nav-item:first-child').addClass('active'); 
    $('.nav-item').find('div').toggleClass(function(){ 
     var className = $(this).attr('class');   
     var classRed = className + '-red';   
     if ($(this).parents().is(".active")) {    
      return classRed ;    
     }else{  
      return className; 

     } 
    }); 
}); 

を強調表示されたとき、私は希望クラスが 'icon-name'から 'icon-name-red'に変更され、別のタブが選択された場合、以前のdivクラスと同じものが 'icon-name'に戻されます。問題は、何か起こるために2回クリックしなければならないクリックイベントを追加することです。

私は誰かがこれを手伝ってくれることを願っています。

おかげ

答えて

0

私は私の問題を解決する方法を発見しなかったので、多分これは誰にも役立ちます。

$(document).ready(function() { 
//activate the first item in the list 
    $('.nav.nav-icons .nav-item:first-child').addClass('active'); 
    $('.nav-item.active').find("div").attr('class',function(i, v) { 
     return v.replace('-white', '-red'); 
    });   
}); 
//this code is for each icon_list 
$(function(){   
    $('.nav-item.list1').unbind('click'); 
    $('.nav-item.list1').on('click', 
    function(){  
     $(this).toggleClass('active');     
     if ($(this).hasClass('active')){ 
      $('.nav-item.list1 ').find("div").attr('class',function(i, v) { 
      return v.replace('-red', '-white'); 
      });    
      $(this).find("div").attr('class',function(i, v) { 
      return v.replace('-white', '-red'); 
      }); 
     } 
     $(this).toggleClass('active');  
    }); 

私には、誰かが優れた解決策を持っているか、あるいは私の改善のためのアイデアがありますように願っています。

関連する問題