Javascript 使用jquery突出显示tr';s或td';s
我有两张桌子:Javascript 使用jquery突出显示tr';s或td';s,javascript,jquery,html,Javascript,Jquery,Html,我有两张桌子: <table class="highlight_row" id="table1"> <tr id="first_row"> <td><input type="checkbox" id="first">first thing</td> <td><input type="checkbox" id="second">second thing</td> &l
<table class="highlight_row" id="table1">
<tr id="first_row">
<td><input type="checkbox" id="first">first thing</td>
<td><input type="checkbox" id="second">second thing</td>
<td><input type="checkbox" id="third">third thing</td>
</tr>
</table>
<table class="highlight_td" id="table2">
<tr id="second_row">
<td><input type="checkbox" id="fourth">fourth thing</td>
<td><input type="checkbox" id="fifth">fifth thing</td>
<td><input type="checkbox" id="sixth">sixth thing</td>
</tr>
</table>
对于行,请使用:
.highlight_row .selected {
background: yellow;
}
对于电池使用:
.highlight_td .selected td:nth-child(1) {
background: yellow;
}
大概是吧
你的HTML
CSS:
JS:
对于第一个表,您需要评估所有复选框,以便它不会不突出显示。第二张桌子容易多了 小提琴:
显示的代码是在整个表的单击处理程序中添加更改处理程序 这将导致复杂的事件,如果用户在表中多次单击,可能会导致严重的浏览器性能问题 简单地说,在表上单击4次,每次更改复选框时,它都会触发4个更改处理程序 行高亮显示的一种简单方法是使用行中复选框的计数来确定类状态
$('table.highlight_row input:checkbox').change(function(){
var $row = $(this).closest('tr'),
hasChecked = $row.find(':checkbox:checked').length;
$row.toggleClass('selected', hasChecked);
});
单元格高亮显示更容易…只需根据选中状态在父单元格上切换类
$('table.highlight_td input:checkbox').change(function(){
$(this).parent().toggleClass('selected', this.checked);
});
发布您的jQuery——我觉得您可能正在为第一个示例选择所有
td
元素。您不能在页面中重复ID…它们在定义上是唯一的。发布不起作用的代码,以便人们可以帮助您找出原因。通过这种方式,您可以学到更多,我们不必重新发明轮子。我们可以看到您的jquery事件调用吗?正如我上面的用户所说,可能是抓错了元素
$("#table1 input[type=checkbox]").on('click', function ()
{
$(this).parent().parent().toggleClass('highlight');
});
$("#table2 input[type=checkbox]").on('click', function ()
{
$(this).parent().toggleClass('highlight');
});
$(function () {
// Highlight Row
$('#table1 input[type="checkbox"]').on('change', function () {
var anyChecked = false;
$(this).closest('tr').find('input[type="checkbox"]').each(function () {
if ($(this).prop('checked')) {
anyChecked = true;
}
});
if (anyChecked) {
$(this).closest('tr').addClass('highlight');
} else {
$(this).closest('tr').removeClass('highlight');
}
});
// Highlight Cell
$('#table2 input[type="checkbox"]').on('change', function () {
var checked = $(this).prop('checked');
if (checked) {
$(this).closest('td').addClass('highlight');
} else {
$(this).closest('td').removeClass('highlight');
}
});
});
$('table.highlight_row input:checkbox').change(function(){
var $row = $(this).closest('tr'),
hasChecked = $row.find(':checkbox:checked').length;
$row.toggleClass('selected', hasChecked);
});
$('table.highlight_td input:checkbox').change(function(){
$(this).parent().toggleClass('selected', this.checked);
});