[英]On Click add Class to First <td> in Row and corresponding <th> in Table
我有一个具有可点击的<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
});
尝试
$(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')
});
});
演示: 小提琴
$('.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');
});
当然可以,您的选择器被告知要执行此操作。
您需要在点击上下文中创建选择器
$(this).parent().find('td:nth-child(1)').addClass('superStyle');
演示: http : //jsfiddle.net/L8s5X/7/
该解决方案似乎可以按需工作:
// 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');
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.