<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>可编辑的表格</title>
<script src="../js/jquery-1.4.2.min.js"></script>
<style>
table{
border: 1px solid black;
border-collapse: collapse;
width: 500px;
}
table th {
border: 1px solid black;
width: 25%;
}
table td {
align-items: center;
border: 1px solid black;
width: 25%;
}
table th {
background-color: #A3BAE9;
}
</style>
<script>
//文档准备就绪
$(function () {
//设置 所有 td 居中
$('table td').attr("align","center");
//标签+属性选择所有<编辑>按钮
$('input[value="编辑"]').click(function () {
//获取每一个<编辑>按钮的 下标(从0开始 所以需要+2 = 按钮在表格的所在行数)
var numId = $('input[value="编辑"]').index($(this))+2;
//选择表格中的所有tr 通过eq方法取得当前tr
var ttr = $('table tr').eq(numId);
/*当前行使用find方法找到每一个td列
each方法为每一个td设置function
*/
ttr.find("td").each(function () {
/*过滤 td中的元素
checkbox 、 button、text 不需要执行append
注意 return 为 跳出当前 each
return false 为 跳出整个 each
*/
if($(this).children("input[type='checkbox']").length>0){
return ;
}
if($(this).children("input[type='button']").length>0){
return ;
}
if($(this).children("input[type='text']").length>0){
return ;
}
var tdText = $(this).html();
$(this).html("");
var inputObj = $("<input type='text'>");
inputObj.appendTo($(this));
inputObj.css("width","95%");
inputObj.val(tdText);
});
})
//为每一个确定按钮设置点击事件
$('input[value="确定"]').click(function () {
/*通过parents方法获取<确定>按钮的父容器tr
再为 tr中的每一个text设置function
*/
var ttr=$(this).parents("tr");
ttr.find('input[type="text"]').each(function () {
var inputVal = $(this).val();
$(this).parents('td').html(inputVal);
})
})
//全选/反选
$('#cha').click(function () {
//判断checkbox是否选中
if($(this).is(':checked')){
$('input[type="checkbox"]').attr("checked","true");
}else{
$('input[type="checkbox"]').removeAttr("checked");
}
})
//新增元素
$('#add').click(function () {
$('table tr').eq(2).clone(true).appendTo("table");
})
$('#del').click(function () {
$('tr:last').remove();
})
})
</script>
</head>
<body>
<input type="button" value="新增" id="add">
<input type="button" value="删除" id="del">
<table border="1">
<thead>
<tr>
<th colspan="4">编辑表格</th>
</tr>
</thead>
<tr>
<th><input type="checkbox" id="cha"></th>
<th>学号</th>
<th>姓名</th>
<th>操作</th>
</tr>
<tr>
<td><input type="checkbox"></td>
<td>000001</td>
<td>张三</td>
<td >
<input type="button" value="编辑" >
<input type="button" value="确定" >
</td>
</tr>
<tr>
<td><input type="checkbox"></td>
<td>000002</td>
<td>李四</td>
<td>
<input type="button" value="编辑" >
<input type="button" value="确定" >
</td>
</tr>
<tr>
<td><input type="checkbox"></td>
<td>000003</td>
<td>王五</td>
<td>
<input type="button" value="编辑" >
<input type="button" value="确定" >
</td>
</tr>
<tr>
<td><input type="checkbox"></td>
<td>000004</td>
<td>赵六</td>
<td>
<input type="button" value="编辑" >
<input type="button" value="确定" >
</td>
</tr>
</table>
</body>
</html>