单击“将类添加到第一个”<td>在行中并且对应<th>表中

On Click add Class to First <td> in Row and corresponding <th> in Table

本文关键字:lt gt 表中 th td 添加 第一个 单击      更新时间:2023-09-26

我有一个表,它有可点击的<td>

当我点击表中的单元格时,我想向添加一个类

  • 我单击的行中的第一个<td>
  • 对应于行所在列的<th>

从本质上讲,我试图直观地显示哪个<td>被点击了。

我可以想出如何将类添加到行中的第一个<td>,但它会将它们全部添加到其中,而不仅仅是我所在的那个。我无法想出如何将其添加到<th>

正在查找有关如何在Jquery中执行此操作的一些建议。我不完整的代码是:

//Adding Class Needed
$('.table-bordered tr td').on('click',function(){
    //Add Class to First TD in ROW
        $("tr td:nth-child(1)").addClass('superStyle');
    //Add Class to Header <th> Cell above
    });

演示http://jsfiddle.net/L8s5X/

尝试

$(function(){
    //Hover and click colors
    var table = $('table').on('click', 'td', function(){
        $('.table-bordered tr td').removeClass('active');
        $(this).addClass('active');
    });
    //Adding Class Needed
    $(table).find('tr td').on('click',function(){
        //Add Class to First TD in ROW
        table.find('.superStyle').removeClass('superStyle');
        $(this).closest('tr').find("td:nth-child(1)").addClass('superStyle');
        //Add Class to Header <th> Cell above
        table.find('thead th').eq($(this).index()).addClass('superStyle')
    });
});

演示:Fiddle

当然是这样,您的选择器会被告知这样做。

您需要在点击的上下文中创建选择器

    $(this).parent().find('td:nth-child(1)').addClass('superStyle');

演示:http://jsfiddle.net/L8s5X/7/

演示

$('.table-bordered tr td').on('click', function () {
        var $table = $(this).closest('table'),
              $tds = $(this).closest('tr').find('td');
        $table.find('.superStyle').removeClass('superStyle');
        //Add Class to First TD in ROW
        $tds.eq(0).addClass('superStyle');
        //Add Class to Header <th> Cell above
        var index = $tds.index(this);
        $table.find('th').eq(index).addClass('superStyle');
    });

此解决方案似乎可以按需工作:

jsfiddle

// save elements before binding the event handler, to save processing time
var $table = $('table'),
    $headings = $table.find('thead th'),
    $fields = $table.find('td');
$table.on('click', 'td', function () {
    var $this = $(this),
        index = $this.index();
    $fields.removeClass('active');
    $this.parent().children(':first-child').addClass('active');
    $headings.removeClass('superStyle').eq(index).addClass('superStyle');
});