2016-05-18 9 views
-1

私は同じようなテーブルを持っています。追加と削除クラスをクリック

<table> 
    <tr> 
     <td>table 1 a <span class="icon"></span></td> 
    </tr> 
    <tr> 
     <td>table 2 b <span class="icon"></span></td> 
    </tr> 
    <tr> 
     <td>table 3 c <span class="icon"></span></td> 
    </tr> 
</table> 

1行目をクリックすると、私のスパンクラスはこのようになります。その後<span class="icon icon-active"></span>

例えば私は2つの私のスパンクラスが<span class="icon icon-active"></span>でなければならない行2]をクリックしますが、行1(アイコン - アクティブ)のスパンが

答えて

3

を削除する必要がありますあなたは、次のようなremoveClass()addClass()メソッドを使用する必要があります。 removeClass(の使用により

$('table tr').click(function() { 
 
    $('table .icon-active').removeClass('icon-active'); 
 
    $('.icon', this).addClass('icon-active'); 
 
})
.icon-active { 
 
    background-color: green; 
 
} 
 
.icon { 
 
    width: 10px; 
 
    height: 10px; 
 
    display: inline-block; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<table> 
 
    <tr> 
 
     <td>table 1 a <span class="icon"></span></td> 
 
    </tr> 
 
    <tr> 
 
     <td>table 2 b <span class="icon"></span></td> 
 
    </tr> 
 
    <tr> 
 
     <td>table 3 c <span class="icon"></span></td> 
 
    </tr> 
 
</table>

-1

)とjQueryのaddClass()メソッド。あなたはそれを動作させることができます。

1)まずスパン

2からクラスを削除)

$('tr').click(function(){ 
 

 
$('span').removeClass('icon-active'); 
 
$(this).find('span').addClass('icon-active'); 
 
});
.icon-active { 
 
    background-color:Blue !important; 
 
    display:inline-block; 
 
} 
 

 
span.icon 
 
{ 
 
    height:10px; 
 
    width:10px; 
 
    background-color:red; 
 
    display:inline-block; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<table> 
 
<tr> 
 
<td>table 1 a <span class="icon"></span></td> 
 
</tr> 
 
<tr> 
 
<td>table 2 b <span class="icon"></span></td> 
 
</tr> 
 
<tr> 
 
<td>table 3 c <span class="icon"></span></td> 
 
</tr> 
 
</table>

をクリックするだけにクラスを追加
関連する問題