版权声明:未经允许,请勿盗用 https://blog.csdn.net/qq_37916164/article/details/84830260
一.后台系统管理表格的全选,反选,查找,选中行
1:html
<input type="text" id="username"><button>查找</button>
<button id="btnFx">反选</button>
<table class="datalist">
<thead>
<tr>
<th width="20"><input type="checkbox" id="all"></th>
<th>姓名</th>
<th>昵称</th>
<th>性别</th>
<th>爱好</th>
</tr>
</thead>
<tbody>
<tr>
<td><input type="checkbox"></td>
<td>刘备</td>
<td>小刘</td>
<td>男</td>
<td>撩妹,装逼,编草鞋</td>
</tr>
<tr>
<td><input type="checkbox"></td>
<td>关羽</td>
<td>关二</td>
<td>男</td>
<td>耍大刀,变脸,喝酒</td>
</tr>
<tr>
<td><input type="checkbox"></td>
<td>张飞</td>
<td>张三</td>
<td>男</td>
<td>打架,喝酒,耍流氓</td>
</tr>
<tr>
<td><input type="checkbox"></td>
<td>赵云</td>
<td>赵四</td>
<td>男</td>
<td>打架,喝酒,耍帅</td>
</tr>
<tr>
<td><input type="checkbox"></td>
<td>貂蝉</td>
<td>美女</td>
<td>女</td>
<td>撩汉,化妆</td>
</tr>
<tr>
<td><input type="checkbox"></td>
<td>小乔</td>
<td>乔二</td>
<td>女</td>
<td>弹琴,唱歌,撩周瑜</td>
</tr>
</tbody>
</table>
2:css
.datalist {
border:1px solid #ccc;
border-collapse:collapse;
width:100%;
}
.datalist thead tr {
background-color:#dfdfdf;
}
td,th {
border:1px solid #ccc;
padding:5px 10px;
}
.odd {
background-color:#efefef;
}
.selected {
background-color:#FFEFBB;
color:#323232;
}
3:js
$(function() {
//点击tr 背景改变 并改变对应的checkbox的状态
$('tbody tr').click(function() {
console.log('click');
console.log(this);
$(this).toggleClass('selected');
//通过样式判断是否有勾选
$(this).find(':checkbox').prop('checked', $(this).hasClass('selected'));
allPD()
})
//全选按钮
$('#all').click(function() {
console.log($(this).prop('checked'));
var bAll = $(this).prop('checked');
if (bAll) {
//全选
$('tbody tr').addClass('selected');
$('tbody :checkbox').prop('checked', true);
} else {
//全不选
$('tbody tr').removeClass('selected');
$('tbody :checkbox').prop('checked', false);
}
})
//反选
$('#btnFx').click(function() {
$('tbody tr').toggleClass('selected');
$('tbody :checkbox').each(function() {
//this 遍历的checkbox js
//通过父节点的父节点 找到tr
console.log($(this).parent().parent().hasClass('selected')) //true false
$(this).prop('checked', $(this).parent().parent().hasClass('selected'))
})
allPD()
})
//查找功能
$('button').eq(-2).click(function() {
//获取输入框的内容
var name = $('#username').val();
if (name == "") {
console.log("输入错误");
} else {
//清除原来的状态
$('tbody tr').removeClass('selected');
$('tbody :checkbox').prop('checked', false);
//匹配对应的td
var $td = $('tbody td:contains(' + name + ')')
//通过td找到对应的tr
$td.parent().addClass('selected').find(':checkbox').prop('checked', true);
}
allPD()
})
//全选状态的修改
function allPD() {
//tr的数量 或者是checkbox的数量
var checkboxLen = $('tbody :checkbox').length;
//所有被勾选的checkbox的数量
var checkedLen = $('tbody :checked').length;
if (checkboxLen == checkedLen) {
$('#all').prop('checked', true);
} else {
$('#all').prop('checked', false);
}
}
});