JQuery控制Html页面Checkbox全选和全不选

年爸 1年前 ⋅ 1129 阅读

说明:Checkbox的全选和全不选应用较为普遍,网上的资料大多数都是原生JS的实现方式,大家你超我,我超你,没意思!今天用JQuery试着写了一下,采用了新的角度实现,供大家参考一下,直接上代码,解释在代码里都写了!

1、Html页面代码

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title></title>
    </head>
    <body>
        <table align="center" style="border:1px dashed #F00;width:50%;height:60px;margin-top:10px">
            <thead>
		<tr>
		    <th><input type="checkbox" id="checkBoxAll" /></th>
		    <th>姓名</th>
		    <th>手机号码</th>
		    <th>部门</th>
		</tr>
            </thead>
            <tbody align="center">
                <tr>
                    <td><input type="checkbox" name="checkBoxs" /></td>
                    <td>张三</td>
                    <td>13000000001</td>
                    <td>技术部</td>
                </tr>
                <tr>
                    <td><input type="checkbox" name="checkBoxs" /></td>
                    <td>李四</td>
                    <td>13000000002</td>
                    <td>技术部</td>
                </tr>
                <tr>
                    <td><input type="checkbox" name="checkBoxs" /></td>
                    <td>王五</td>
                    <td>13000000003</td>
                    <td>技术部</td>
                </tr>
                <tr>
                    <td><input type="checkbox" name="checkBoxs" /></td>
                    <td>赵六</td>
                    <td>13000000004</td>
                    <td>人事部</td>
                </tr>
                <tr>
                    <td><input type="checkbox" name="checkBoxs" /></td>
                    <td>田七</td>
                    <td>13000000005</td>
                    <td>财务部</td>
                </tr>
            </tbody>
        </table>
    </body>
</html>

2、JavaScript代码

<script type="text/javascript" src="jquery-3.4.1.min.js" ></script>
<script>    
	$(function() {
		// 全选/全不选
		$("#checkBoxAll").click(function() {
			$(":checkbox[name='checkBoxs']").prop("checked", this.checked); //所有checkbox使用checkBoxAll状态
		});

		// checkbox全部选中时,checkBoxAll选中;checkbox存在未选中时,checkBoxAll不选 
		$(":checkbox[name='checkBoxs']").click(function(){
			// 首先验证自己是否选中状态,如果自己为非选中状态,则直接改变checkBoxAll状态					
			if(!$(this)[0].checked){
				$("#checkBoxAll").prop("checked", false);
				return;
			}
			
			// 整体验证
			// 获取未选中的checbox,如果存在则非全选
			var checkBoxslist = $(":checkbox[name='checkBoxs']:not(:checked)");
			if(checkBoxslist.length > 0){ // 存在未选中
				$("#checkBoxAll").prop("checked", false);
			}else{ // 不存在未选中
				$("#checkBoxAll").prop("checked", true);
			}
		});
	}); 
</script>

# 案例下载地址,URL:https://pan.baidu.com/s/14Xh4oKmTkDtWH2N6wLTPNw   提取码:g4rc

如果想看效果,把HTML和JavaScript部分组合在一起,在引入自己的JQuery文件就行了(我也不想写这句废话,但是有人问过我怎么看效果......)!


全部评论: 0

    我有话说: