使用jQuery将表格单元格的背景更改为不同的颜色

时间:2012-12-11 19:49:36

标签: jquery css

我有一张这样的表:

installment table

我想用点击它们的价格(例如addClass(on))更改单元格的背景颜色,如左下角所示,还可以更改背景颜色其他单元格(例如addClass(off))。

我不希望其他细胞受影响(具有文字和不同颜色的细胞)。

我还需要获取被点击的单元格所属的行的ID。

这是一行的结构。

<tr class="taksit" id="tek">
    <td><b>Tek Çekim</b></td>
    <td><?=$sontutar?> TL</td>
    <td><?=$sontutar?> TL</td>
    <td><?=$sontutar?> TL</td>
    <td><?=$sontutar?> TL</td>
    <td><?=$sontutar?> TL</td>
    <td><?=$sontutar?> TL</td>
    <td><?=$sontutar?> TL</td>
</tr>

我在这里尝试了一些技巧,但无法做到。 不知道怎么办?

2 个答案:

答案 0 :(得分:1)

$('table#uniqueID tbody td').on('click',function() {
    $(this).closest('tbody').find('td').removeClass('highlight');
    $(this).addClass('highlight');
});

答案 1 :(得分:1)

$("#table_selector td.clickable").on('click',function(){
  // cache $(this)
  var clickedElement = $(this);

  // remove background color from other clickable items 
  $("td.clickable").css('background','none');

  // change the background color of the clicked <td>    
  clickedElement.css('background','red');

  var rowId = clickedElement.closest('tr').attr('id');
});

让我解释一下我在这里做了些什么 首先,您说您不希望每个<td>受到这些点击和背景更改的影响。因此,您应该为所有{“1}}”提供一个“可点击”的课程,然后您可以将<td>事件限制为您想要的元素。你当然也可以做相反的事情,为你想要忽略的人添加一个“noClick”类......

更改on('click')的背景颜色可以通过几种方式完成,我为了举例而选择使用简单的<td>,但我相信你还有更多实际代码中的逻辑。

通过使用closest()函数查找最近的父.css('background','red');父元素来提取rowId。然后只需查看<tr>属性。