点击每一行的时候,就会选中第一列的单选框按钮,点击全选就全部选中,如果全部选中了,全选按钮也自动选中
代码如下:
<%@ page language="java" pageEncoding="UTF-8"%>
<%@ taglib uri="/struts-tags" prefix="s"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<base href="<%=basePath%>">
<title></title>
<script src="js/jquery-1.9.1.min.js" type="text/javascript" ></script>
<title>全选</title>
<script language="javascript" type="text/javascript">
$(function(){
checkBox("items","selectAll","a");
});
//checkBoxName的name名称,checkboxId全选框Id
function checkBox(checkBoxName,checkboxId,trClass){
//获取多选框的对象
var checkbox = $(':checkbox[name='+checkBoxName+']');
//获取行对象
var row = $('.'+trClass+'');
/**点击全选或全部不选**/
$('#'+checkboxId+'').click(function(){
checkbox.add($('#'+checkboxId+'')).prop('checked', this.checked);
});
/**选框的点击事件**/
checkbox.click(function(e){
//阻止冒泡,避免行点击事件中,直接选择选框无效
e.stopPropagation();
//判断选中个数与实际个数是否相同,以确定全选/全不选状态
$('#'+checkboxId+'').prop('checked', checkbox.size() == checkbox.filter(':checked').size());
});
row.bind({
//点选
click: function(){
//行内点击时,行内的选框状态为原状态取反
$(this).find(':checkbox').prop('checked', !$(this).find(':checkbox').get(0).checked)
$('#'+checkboxId+'').prop('checked', checkbox.size() == checkbox.filter(':checked').size());
}
});
}
</script>
<style>
</style>
</head>
<body>
<form action="" id="form1">
<div id="demo">
<table id="tables">
<tr class="a"> <td><input type="checkbox" value="歌曲1" name="items"/>歌曲1</td><td>dafdfdfdsss</td></tr>
<tr class="a"> <td><input type="checkbox" value="歌曲1" name="items"/>歌曲2</td><td>dfadfadsss</td></tr>
<tr class="a"> <td><input type="checkbox" value="歌曲2" name="items"/>歌曲3</td><td>sadfadfadfss</td></tr>
</table>
<input name="name" value="zfc">
<input type="checkbox" value="全选" id="selectAll" />all
</div>
<input type="button" οnclick="save()">
</form>
</body>
</html>