td内部元素的onClick toggleClass和removeClass用于同级td内部元素

时间:2018-08-24 09:32:20

标签: javascript jquery

1),我想将class('unmuted')切换到tr td元素中的标签 2),当我单击另一个tr td元素中的另一个标签时,将类删除到以前的标签中,然后将类添加到当前元素中

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
<style type="text/css">
.unmuted{background: #ff0000;}
</style>
</head>

<body>
<table class="myTable" border="1" cellpadding="10">
    <thead>
        <tr>
            <th>Actions</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td align="center">
                <a class="unmute" href="javascript:void(0)"><img src="https://cdn0.iconfinder.com/data/icons/typicons-2/24/microphone-512.png" width="16"></a>
            </td>
        </tr>
        <tr>
            <td align="center">
                <a class="unmute unmuted" href="javascript:void(0)"><img src="https://cdn0.iconfinder.com/data/icons/typicons-2/24/microphone-512.png" width="16"></a>
            </td>
        </tr>
        <tr>
            <td align="center">
                <a class="unmute" href="javascript:void(0)"><img src="https://cdn0.iconfinder.com/data/icons/typicons-2/24/microphone-512.png" width="16"></a>
            </td>
        </tr>
    </tbody>
</table>
<script type="text/javascript">
    $(".myTable").on('click','a', function(){
        $(this).toggleClass('unmuted').closest('tr').find('a').removeClass('unmuted');
        //$(this).addClass('unmuted');
     })
</script>
</body>
</html>

1 个答案:

答案 0 :(得分:3)

您可以选择当前具有unmuted类的任何元素以及当前元素(通过使用add()),然后在其上调用toggleClass。包括当前元素在内的那些元素将被关闭,而没有元素的元素将被打开。

$('.unmute').click(function(){
  $('.unmuted').add(this).toggleClass('unmuted');
});
.unmuted {
  background:#ff0000;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table class="myTable" border="1" cellpadding="10">
    <thead>
        <tr>
            <th>Actions</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td align="center">
                <a class="unmute" href="javascript:void(0)"><img src="https://cdn0.iconfinder.com/data/icons/typicons-2/24/microphone-512.png" width="16"></a>
            </td>
        </tr>
        <tr>
            <td align="center">
                <a class="unmute unmuted" href="javascript:void(0)"><img src="https://cdn0.iconfinder.com/data/icons/typicons-2/24/microphone-512.png" width="16"></a>
            </td>
        </tr>
        <tr>
            <td align="center">
                <a class="unmute" href="javascript:void(0)"><img src="https://cdn0.iconfinder.com/data/icons/typicons-2/24/microphone-512.png" width="16"></a>
            </td>
        </tr>
    </tbody>
</table>

相关问题