今天学习了利用jQuery实现可以编辑的表格这个例子。这个例子需求是这样的:在前台的表格中单击单元格便可修改其中的内容,回车键保存修改的内容,esc撤销保存的内容。原理:单击客户端表格单元格时,在单元格中添加一个文本框,并将单元格中原来的内容赋值给文本框,再进一步去修改文本框内容,修改后将文本框内容重新赋值给单元格。
源码:
前台代码:
<%@ Page Language=”C#” AutoEventWireup=”true” CodeBehind=”WebForm1.aspx.cs” Inherits=”WebApplication1.WebForm1″ %>
<!DOCTYPE html
<html xmlns=”http://www.w3.org/1999/xhtml”>
<head runat=”server”>
<meta http-equiv=”Content-Type” content=”text/html; charset=utf-8″/>
<title>jq2—可以编辑的表格</title>
<link href=”css/editTable.css” rel=”stylesheet” />
<script type=”text/javascript” src=”js/jquery.js”></script>
<script type=”text/javascript” src=”js/editTable.js”></script>
<%–<script type=”text/javascript” src=”js/jquery-1.9.1.js”></script>–%>
</head>
<body>
<form id=”form1″ runat=”server”>
<div>
<table>
<thead>
<tr>
<th colspan=”2″>鼠标点击表格项就可以编辑</th>
</tr>
</thead>
<tbody>
<tr>
<th>学号</th>
<th>姓名</th>
</tr>
<tr>
<td>000001</td>
<td>张三</td>
</tr>
<tr>
<td>000002</td>
<td>李四</td>
</tr>
<tr>
<td>000003</td>
<td>王五</td>
</tr>
<tr>
<td>000004</td>
<td>赵六</td>
</tr>
</tbody>
</table>
</div>
</form>
</body>
</html>
css代码:
body {
}
table {
border:1px solid #000000;
border-collapse:collapse;/*单元格边框合并*/
width:400px;
}
table td {
border:1px solid #000000;
width:50%;
}
table th {
border:1px solid #000000;
width:50%;
}
tbody th {
background-color:#426fae;
}
jquery代码
$(function () {
//找到表格中除了第一个tr以外的所有偶数行
//使用even为了通过tbody tr返回所有tr元素
$(“tbody tr:even”).css(“background-color”, “#ece9d8”);
//找到所有的学号单元格
var numId = $(“tbody td:even”);
//给单元格注册鼠标点击事件
numId.click(function () {










