点击tr选中每一行前面的checkbox

这篇博客介绍如何使用jQuery实现表格行点击时改变背景颜色并选中该行对应的checkbox。通过隔行变色增加表格可读性,并提供点击行时切换checkbox选中状态的交互效果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

<style type="text/css">
.blue {
background: #006CB7;
}

.pox {
background: #255625;
}
</style>
<table class="table" id="itemList">
<thead>
<tr>


<th>Table heading</th>
<th>Table heading</th>
<th>Table heading</th>
<th>Table heading</th>
<th>Table heading</th>
<th>Table heading</th>
</tr>
</thead>
<tbody>
<tr>


<td>Table cell</td>
<td>Table cell</td>
<td>Table cell</td>
<td>Table cell</td>
<td>Table cell</td>
<td>Table cell</td>
</tr>
<tr>
<tr>


<td>Table cell</td>
<td>Table cell</td>
<td>Table cell</td>
<td>Table cell</td>
<td>Table cell</td>
<td>Table cell</td>
</tr>
<tr>


<td>Table cell</td>
<td>Table cell</td>
<td>Table cell</td>
<td>Table cell</td>
<td>Table cell</td>
<td>Table cell</td>
</tr>
</tbody>
</table>


<table class="table table-bordered" id="table">
<thead>
<tr>
<th>#</th>
<th>Table heading</th>
<th>Table heading</th>
<th>Table heading</th>
<th>Table heading</th>
<th>Table heading</th>
<th>Table heading</th>
</tr>
</thead>
<tbody>
<tr>
<tr>
<td><label>
  <input type="checkbox" id="inlineCheckbox1" value="option1"> 
</label></td>
<td>Table cell</td>
<td>Table cell</td>
<td>Table cell</td>
<td>Table cell</td>
<td>Table cell</td>
<td>Table cell</td>
</tr>
<tr>
<tr>
<td><label>
  <input type="checkbox" id="inlineCheckbox1" value="option1"> 
</label></td>
<td>Table cell</td>
<td>Table cell</td>
<td>Table cell</td>
<td>Table cell</td>
<td>Table cell</td>
<td>Table cell</td>
</tr>
<tr>

<td><label>
  <input type="checkbox" id="inlineCheckbox1" value="option1"> 
</label></td>
<td>Table cell</td>
<td>Table cell</td>
<td>Table cell</td>
<td>Table cell</td>
<td>Table cell</td>
<td>Table cell</td>
</tr>
</tbody>
</table>


<script type="text/javascript" src="js/jquery.min.js"></script>
<script type="text/javascript">
//隔行变色
$("#itemList tr").each(function(i) {
this.style.color = ['red', '#faf'][i % 2];
})
$(function() {
//点击一行加色选中checkbox
$("#table tr").click(function() {
var hasSelected = $(this).hasClass("blue");
$(this)[hasSelected ? "removeClass" : "addClass"]("blue").find(":checkbox").prop("checked", !hasSelected);
})


});
</script>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

lilinlin123

总结不易,赏杯水钱

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值