单击“添加”和“删除类”

时间:2016-05-18 11:41:26

标签: javascript jquery css

我有桌子就像;

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

如果我点击第一行,我的span类必须是这样的; <span class="icon icon-active"></span>

之后,例如我单击第二行,我的两个span类必须是<span class="icon icon-active"></span>,但第一行(icon-active)的跨度必须删除

2 个答案:

答案 0 :(得分:3)

您应该使用removeClass()addClass()等方法。

&#13;
&#13;
$('table tr').click(function () {
    $('table .icon-active').removeClass('icon-active');
    $('.icon', this).addClass('icon-active');
})
&#13;
.icon-active {
    background-color: green;
}
.icon {
    width: 10px;
    height: 10px;
    display: inline-block;
}
&#13;
<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>
&#13;
&#13;
&#13;

答案 1 :(得分:-1)

使用jquery的removeClass()和addClass()方法。你可以让它发挥作用。

1)首先从所有范围中删除课程

2)只将一个类添加到一个被点击的

&#13;
&#13;
$('tr').click(function(){

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

span.icon
{
  height:10px;
  width:10px;
  background-color:red;
    display:inline-block;
}
&#13;
<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>
&#13;
&#13;
&#13;