JQuery兄弟姐妹()。仅将类添加到任何行中的单击列

时间:2016-08-17 07:27:19

标签: jquery siblings

它为每一行工作。如何从任何一行只使用一次? 仅将类添加到任何行中的单击列,并且所有tr类中的所有其他td都应为空。 请帮忙

$('td').click(function(){
    $(this).siblings('td').removeClass('active');
    $(this).addClass('active');
});

http://jsfiddle.net/5QsCy/3/

3 个答案:

答案 0 :(得分:1)

为什么不在所有active上删除td类,然后再将其设置为新单元格?

$('td').click(function(){
    $('td').removeClass('active');
    $(this).addClass('active');
});
.active {
  border: solid 1px red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
  <tr>
    <td>COL</td>
    <td>COL</td>
  </tr>
  <tr>
    <td>COL</td>
    <td>COL</td>
  </tr>
  <tr>
    <td>COL</td>
    <td>COL</td>
  </tr>
<table>

答案 1 :(得分:0)

您需要从所有active元素中删除td类。截至目前,您只从兄弟td元素中删除该类。

$('td').click(function(){
    $('td.active').removeClass('active'); //Remove active class from all td
    $(this).addClass('active');
});

DEMO

答案 2 :(得分:-1)

$('#xyz td').click(function(){
    $("#xyz").find('td').removeClass('active');
    $(this).addClass('active');
});

HTML: -

 <table id="xyz">
    <tr><td>COL</td><td>COL</td></tr>
    <tr><td>COL</td><td>COL</td></tr>
    <tr><td>COL</td><td>COL</td></tr>
    <table>

CSS: -

.active {border:solid 1px red;}

DEMO