jQuery操作表格简单示例:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>jQuery学习 操作表格</title>
<style type="text/css">
html,body{
font-size: 13px;
}
table{
width:500px;
text-align:center;
font-size: 13px;
border-collapse:collapse;
border-color: #7c7b81;
}
.odd{
background-color: #CFD0D4;
}
.over{
background-color:#E6ECF5;
color:#F00;
}
</style>
</head>
<body>
<table id="userTable" border="1">
<thead>
<tr>
<th width="50"><input class="checkAll" type="checkbox" title="全选与反选"/></th>
<th>ID</th>
<th>用户名</th>
<th>角色</th>
<th>创建日期</th>
</tr>
</thead>
<tbody>
<tr>
<td><input type="checkbox" name="userId" /></td>
<td>1</td>
<td>admin</td>
<td>系统管理员</td>
<td>2010-09-08</td>
</tr>
<tr>
<td><input type="checkbox" name="userId" /></td>
<td>2</td>
<td>admin</td>
<td>系统管理员</td>
<td>2010-09-08</td>
</tr>
<tr>
<td><input type="checkbox" name="userId" /></td>
<td>3</td>
<td>admin</td>
<td>系统管理员</td>
<td>2010-09-08</td>
</tr>
<tr>
<td><input type="checkbox" name="userId" /></td>
<td>4</td>
<td>admin</td>
<td>系统管理员</td>
<td>2010-09-08</td>
</tr>
<tr>
<td><input type="checkbox" name="userId" /></td>
<td>5</td>
<td>admin</td>
<td>系统管理员</td>
<td>2010-09-08</td>
</tr>
</tbody>
</table>
<input id="add" type="button" value="新增"/>
<input id="del" type="button" value="删除"/>
<script type="text/javascript" src="js/jquery-1.4.2.min.js"></script>
<script type="text/javascript" src="js/common.js"></script>
<script type="text/javascript">
function chgColor(tableId,bgColor,hoverColor){
$("#"+tableId+" tbody tr:odd").css("background-color",bgColor);
$("#"+tableId+" tbody tr").each(function(){
var oldBgColor = $(this).css("background-color");
$(this).mouseover(function(){
$(this).css("background-color",hoverColor);
});
$(this).mouseout(function(){
$(this).css("background-color",oldBgColor);
});
});
}
$(document).ready(function(){
chgColor("userTable","#CFD0D4","#E6ECF5");
$(".checkAll").click(function(){
if( $(this).attr("checked")){
$("[name=userId]").attr("checked","true");
} else {
$("[name=userId]").each(function(){
if( $(this).attr("checked") ){
$(this).removeAttr("checked");
} else {
$(this).attr("checked","true");
}
});
}
});
$("#add").click(function(){
var user = {"id":"6",
"name":"lql",
"role":"系统管理员",
"createDate":"2010-9-10"
};
$("#userTable tbody").append("<tr><td><input type='checkbox' name='userId' /></td>"+
"<td>"+user.id+"</td>"+
"<td>"+user.name+"</td>"+
"<td>"+user.role+"</td>"+
"<td>"+user.createDate+"</td>");
chgColor("userTable","#CFD0D4","#E6ECF5");
});
$("#del").click(function(){
$("[name=userId]:checked").each(function(){
$(this).parent().parent().remove();
});
chgColor("userTable","#CFD0D4","#E6ECF5");
});
});
</script>
</body>
</html>