我们这里要用jquery实现动态创建表格效果,全部代码奉献给各位。
首先我们来看一下表格的功能:
1、添加
2、删除
3、获取值
4、动态填充数据
5、动态设置焦点
6、键盘左右上下键控制单元格焦点
7、单元格添加正则验证功能
下面是全部文件的代码:
WebForm4.aspx Code:
1 <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm4.aspx.cs" Inherits="table.WebForm4" %>
2
3 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "">
4
5 <html xmlns="" >
6 <head runat="server">
7 <title></title>
8 <script src="jquery-1.3.2-vsdoc2." type="text/"></script>
9 <script src="jquery-1.3.2.js" type="text/javascript"></script>
10 <script src="jquery.DynamicTable.js" type="text/javascript"></script>
11 <link href="style2.css" _fcksavedurl=""style2.css"" type="text/css" rel="Stylesheet"/>
12 <script type="text/javascript">
13 var rowtmplate = "<tr><td><input type='text'/></td>";
14 rowtmplate += "<td><input type='text'/></td>";
15 rowtmplate += "<td><input type='text'/></td>";
16 rowtmplate += "<td><input type='text'/></td>";
17 rowtmplate += "<td><input type='text'/></td>";
18 rowtmplate += "<td><a href='#' >删除</a></td></tr>";
19
20 $(document).ready(function() {
21
22 $(this).bind('keyup', function(e) {
23 switch (e.keyCode) {
24 case 38: //上 ↑
25 var arr = $.fn.getFocus();
26 var rowIndex = arr[0] - 1;
27 $.fn.setFocus({ rowIndex: rowIndex, colIndex: arr[1] });
28 $.fn.setCellsFocus();
29 break;
30 case 40: //下 ↓
31 var arr = $.fn.getFocus();
32 var rowIndex = arr[0] + 1;
33 $.fn.setFocus({ rowIndex: rowIndex, colIndex: arr[1] });
34 $.fn.setCellsFocus();
35 break;
36 default:
37 break;
38
39 }
40 });
41 $('#mytbl').DynamicTable({
42 rowCount: 3, //添加行数
43 identity: 1, //第1列自动编号
44 arrFocus: [2, 1], //第一个单元格设置为焦点
45 rowTmplate: rowtmplate //行模版
46 });
47
48 $('#mytbl').BindEvent({
49 eventName: "click",
50 colIndex: 1,
51 fn: alertMsg
52 }); //默认给第一列绑定click事件
53 $('#mytbl').setCellsFocus(); //设置第一个单元格为焦点
54 $('#mytbl').deleteRow(); //默认给第6列绑定删除事件
55 $('#mytbl').AutoFillData({ colIndex: 2, fn: getData }); //默认给第二列绑定自动填充数据
56 $('#mytbl').Identity({ colIndex: 1 }); //默认给第一列自动排序
57 $('#mytbl').validationText({ reg: /^((\d+\.\d{2})|\d+)$/, colIndex: 5, defalutValue: 0.00 }); //默认给第二列添加验证(只能输入money格式)
58 });
59 //添加行
60 function addRow(count) {
61 $('#mytbl').addRow({ rowCount: count });
62 $('#mytbl').Identity();
63 $.fn.deleteRow();
64 }
65 //获取自动填充数据
66 function getData(key) {
67 var arr = [];
68 arrFoucs = $.fn.getFocus();
69
70 $.({
71 type: "post",
72 async: false, //控制同步
73 url: "getData.ashx",
74 dataType: "json",
75 cache: false,
76 success: function(data) {
77 var idx = arrFoucs[0] - 2;
78 arr.push(data[idx].id);
79 arr.push(data[idx].Name);
80 arr.push(data[idx].Code);
81 arr.push(data[idx].Units);
82 arr.push(data[idx].Price);
83 },
84 Error: function(err) {
85 alert(err);
86 }
87 });
88 $.fn.setCellsFocus({ rowIndex: arrFoucs[0], colIndex: 4 });
89 return arr;
90 }
91 function alertMsg() {
92 arrFoucs = $.fn.getFocus();
93 alert('你单击了坐标X:'+arrFoucs[0]+' Y:'+arrFoucs[1]+'的单元格');
94 }
95 </script>
96 </head>
97 <body>
98 <form id="form1" runat="server">
99 <div>
100 <table cellpadding="0" cellspacing="0" class="tablestyle1" id="mytbl">
101 <tr>
102 <td class="TableData">序号</td>
103 <td class="TableData">产品名称</td>
104 <td class="TableData">产品代码</td>
105 <td class="TableData">单位</td>
106 <td class="TableData">单价</td>
107 <td class="TableData"><a href="#" onclick="addRow(5);">添加5行</a></td>
108 </tr>
109 </table>
110
111 <input type="button" value="获取值" onclick="javascript:alert($.fn.getValue({}));" />
112 </div>
113 </form>
114 </body>
115 </html>
jquery.DynamicTable.js Code:
1 ///<reference path="jquery-1.3.2-vsdoc2.js" />
2
3 (function($) {
4 var rowtmplate = "";
5 var arrFocus = [];
6
7 $.fn.DynamicTable = function(options) { //定义插件的名称,这里为userCp
8 var deafult = {
9 //以下为该插件的属性及其默认值
10 rowCount: 5, //添加行数
11 identity: 1, //第1列自动编号
12 arrFocus: [2, 1], //第一个单元格设置为焦点
13 rowTmplate: "" //行模版
14 };
15 var ops = $.extend(deafult, options);
16 rowtmplate = ops.rowTmplate;
17 arrFocus = ops.arrFocus;
18 $(this).addRow(ops.rowCount);
19 };
20
21 /*通过行模版添加多行至表格最后一行后面*/
22 /*count--添加行数*/
23 $.fn.addRow = function(options) {
24 var deafult = {
25 rowCount: 5
26 };
27 var ops = $.extend(deafult, options);
28
29 var rowData = "";
30 var count = ops.rowCount;
31 for (var i = 1; i <= count; i++) {
32 rowData += rowtmplate;
33 }
34 $(this).find('tr:last-child').after(rowData);
35 CellsFocus();
36 };
37 /*动态给某列绑定事件,事件被触发时执行fn函数*/
38 /*eventName--事件名称;colIndex--列索引(从1开始);fn--触发函数*/
39 $.fn.BindEvent = function(options) {
40 var deafult = {
41 eventName: 'click',
42 colIndex: 1,
43 fn: function() { alert('你单击了此单元格!') }
44 };
45 var ops = $.extend(deafult, options);
46 eventName = ops.eventName;
47 colIndex = ops.colIndex;
48 fn = ops.fn;
49 $("tr:gt(0) td:nth-child(" + colIndex + ")").bind(eventName, fn);
50 };
51 /*给某列绑定单击删除事件*/
52 /*colIndex--列索引(从1开始)*/
53 $.fn.deleteRow = function(options) {
54 var deafult = {
55 colIndex: 6
56 };
57 var ops = $.extend(deafult, options);
58 var colIndex = ops.colIndex;
59
60 $("tr:gt(0) td:nth-child(" + colIndex + ")").bind("click", function() {
61 var obj = $(this).parent(); //获取tr子节点对象
62 if (confirm('您确定要删除吗?'))
63 obj.remove();
64 });
65 };
66 /*自动给指定列填充序号*/
67 /*colIndex--列索引(从1开始)*/
68 $.fn.Identity = function(options) {
69 var deafult = {
70 colIndex: 1
71 };
72 var ops = $.extend(deafult, options);
73 var colIndex = ops.colIndex;
74
75 var i = 1;
76 $("td:nth-child(" + colIndex + ")").find('input').each(function() {
77 $(this).attr('value', i)
78 i++;
79 });
80 };
81 /*获取焦点单元格坐标*/
82 $.fn.getFocus = function() {
83 return arrFocus;
84 };
85 /*设置焦点单元格坐标*/
86 /*rowIndex--行索引(从1开始);colIndex--列索引(从1开始)*/
87 $.fn.setFocus = function(options) {
88 var deafult = {
89 rowIndex: 2,
90 colIndex: 1
91 };
92 var ops = $.extend(deafult, options);
93 var rowIndex = ops.rowIndex;
94 var colIndex = ops.colIndex;
95 arrFocus[0] = rowIndex;
96 arrFocus[1] = colIndex;
97 };
98 /*当某个单元格中输入数据,按Enter键后自动根据输入的值从后台检索数据填充到该行对应列*/
99 /*colIndex--第几列输入数据按Enter键触发事件;fn--带参的回调函数*/
100 $.fn.AutoFillData = function(options) {
101 colIndex = options.colIndex;
102 fn = options.fn;
103 $("td:nth-child(" + colIndex + ")").bind("keyup", function() {
104 var obj = $(this).parent(); //获取tr子节点对象
105 $(this).find('input').each(function() {
106 if (event.keyCode == 13) {
107 var vl = $(this).val();
108 var arr = new Array();
109 arr = fn(vl);
110 var i = 0;
111 obj.find("td").each(function() {
112 $(this).find("input").each(function() {
113 $(this).attr('value', arr[i]);
114 i++;
115 });
116 });
117 }
118 });
119 });
120 };
121 /*设置某个单元格为焦点*/
122 /*rowIndex--行索引(从1开始);colIndex--列索引(从1开始)*/
123 $.fn.setCellsFocus = function(options) {
124 var deafult = {
125 rowIndex: arrFocus[0],
126 colIndex: arrFocus[1]
127 };
128 var ops = $.extend(deafult, options);
129 var rowIndex = ops.rowIndex;
130 var colIndex = ops.colIndex;
131
132 $("tr:nth-child(" + rowIndex + ") td:nth-child(" + colIndex + ")").each(function() {
133 $(this).find('input').each(function() {
134 $(this)[0].focus();
135 $(this).attr('value', $(this).attr('value'));
136 arrFocus = [];
137 arrFocus.push(rowIndex);
138 arrFocus.push(colIndex); //更新焦点数组值
139 });
140 });
141 };
142 /*设置某个单元格文本值为选中状态*/
143 /*rowIndex--行索引(从1开始);colIndex--列索引(从1开始)*/
144 $.fn.setCellsSelect = function(options) {
145 var deafult = {
146 rowIndex: arrFocus[0],
147 colIndex: arrFocus[1]
148 };
149 var ops = $.extend(deafult, options);
150 var rowIndex = ops.rowIndex;
151 var colIndex = ops.colIndex;
152
153 $("tr:nth-child(" + rowIndex + ") td:nth-child(" + colIndex + ")").each(function() {
154 $(this).find('input').each(function() {
155 $(this)[0].select();
156 });
157 });
158 };
159 /*某个单元格添加验证功能*/
160 /*reg--正则表达式;colIndex--列索引(从1开始);defaultValue--验证失败默认给单元格赋值*/
161 $.fn.validationText = function(options) {
162 var deafult = {
163 reg: /^((\d+\.\d{2})|\d+)$/,
164 colIndex: 2,
165 defaultValue: 0
166 };
167 var ops = $.extend(deafult, options);
168 var reg = ops.reg;
169 var colIndex = ops.colIndex;
170 var defaultValue = ops.defaultValue;
171
172 $("tr:gt(0) td:nth-child(" + colIndex + ")").each(function() {
173 $(this).find('input').each(function() {
174 //验证
175 $(this).bind('blur', function() {
176 var vl = $(this).attr('value');
177 if (!reg.test(vl))
178 $(this).attr('value', defaultValue);
179 });
180 });
181 });
182 };
183 /*获取表格中的值*/
184 $.fn.getValue = function(options) {
185 var deafult = {
186 rowIndex: 0, //行坐标(从2开始)
187 colIndex: 0 //列坐标(从1开始)
188 };
189 var ops = $.extend(deafult, options);
190 rowIndex = ops.rowIndex;
191 colIndex = ops.colIndex;
192 var val = "";
193 if (rowIndex == 0) { //获取所有行的数据
194 $('tr:gt(0)').each(function() {
195 $(this).find("td").each(function() {
196 $(this).find("input").each(function() {
197 val += $(this).attr('value') + "&";
198 });
199 });
200 val = val.substring(0, val.length - 1) + "|";
201 });
202 }
203 else {
204 if (colIndex == 0) { //获取某行数据
205 $('tr:nth-child(' + rowIndex + ')').each(function() {
206 $(this).find("td").each(function() {
207 $(this).find("input").each(function() {
208 val += $(this).attr('value') + "&";
209 });
210 });
211 val = val.substring(0, val.length - 1) + "|";
212 });
213 }
214 else { //获取某个单元格的值
215 $("tr:nth-child(" + rowIndex + ") td:nth-child(" + colIndex + ")").each(function() {
216 $(this).find('input').each(function() {
217 val += $(this).attr('value');
218 });
219 });
220 }
221 }
222 return val;
223 };
224 /*某个单元格获取焦点后更新焦点坐标*/
225 function CellsFocus() {
226 var colCount = $("tr:nth-child(1) td").size(); //获取每行共有多少个单元格
227 $("tr:gt(0) td").each(function() {
228 var obj = $(this);
229 $(this).find('input').each(function() {
230 $(this).bind('focus', function() {
231 var cellTotal = $('td').index(obj); //获取某单元格的索引
232 arrFocus[0] = parseInt(cellTotal / colCount) + 1; //第几行
233 arrFocus[1] = cellTotal % colCount + 1; //第几列
234 });
235 });
236 });
237 };
238 })(jQuery);
getData.ashx Code:
1 using System;
2 using System.Collections.Generic;
3 using System.Linq;
4 using System.Web;
5 using System.Web.Services;
6
7 namespace table
8 {
9 /// <summary>
10 /// $codebehindclassname$ 的摘要说明
11 /// </summary>
12 [WebService(Namespace = "")]
13 [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
14 public class getData : IHttpHandler
15 {
16
17 public void ProcessRequest(HttpContext context)
18 {
19 context.Response.Clear();
20 string value = GetResult();
21 context.Response.Write(value);
22 context.Response.End();
23 }
24
25 private string GetResult()
26 {
27 string result = string.Empty;
28
29 result = @"
30 [{""id"":""1"",""Name"":""绿茶"",""Code"":""1371"",""Units"":""斤"",""Price"":""200""},
31 {""id"":""2"",""Name"":""红茶"",""Code"":""1372"",""Units"":""斤"",""Price"":""300""},
32 {""id"":""3"",""Name"":""茶具"",""Code"":""1373"",""Units"":""台"",""Price"":""20000""},
33 {""id"":""4"",""Name"":""铁观音"",""Code"":""1374"",""Units"":""瓶"",""Price"":""400""},
34 {""id"":""5"",""Name"":""袋泡茶"",""Code"":""1375"",""Units"":""盒"",""Price"":""500""},
35 {""id"":""6"",""Name"":""茶食品"",""Code"":""1376"",""Units"":""盒"",""Price"":""400""},
36 {""id"":""7"",""Name"":""包装袋"",""Code"":""1377"",""Units"":""盒"",""Price"":""100""}]";
37
38 return result;
39 }
40
41 public bool IsReusable
42 {
43 get
44 {
45 return false;
46 }
47 }
48 }
49 } style2.css Code:
1 /* ---------- 页面样式定义 ---------- */
2 body
3 {
4 background-color:#ffffff;
5 MARGIN:0px;
6 font-size: 10pt; /* 字体大小 */
7 font-family:Verdana; /* 字体名称 */
8 }
9
10 /* ---------- 文字链接 - 链接的普通状态 ---------- */
11 A:link {
12 color: #0000FF;
13 TEXT-DECORATION: none;}
14
15 /* ---------- 文字链接 - 已被访问链接 ---------- */
16 A:visited {
17 COLOR: #0000FF;
18 TEXT-DECORATION: none}
19
20 /* ---------- 文字链接 - 处于活动状态链接 ---------- */
21 A:active {
22 COLOR: #3333ff;
23 TEXT-DECORATION: none}
24
25 /* ---------- 文字链接 - 指针在链接上 ---------- */
26 A:hover {
27 COLOR: #ff0000;
28 text-decoration: underline;}
29
30 /* ---------- 表格样式1(普通表格) ---------- */
31 .tablestyle1{
32 font-size: 9pt; /* 表格内字体大小 */
33 width: 100%; /* 表格宽度 */
34 border: 0px none; /* 表格边框宽度 */
35 background-color: #0077B2; /* 表格线颜色 */
36 cellSpacing:expression(this.cellSpacing=1); /* 两个单元格之间的距离 */
37 cellPadding:expression(this.cellPadding=3); }
38
39
40 .TableData {
41 BACKGROUND: #FFFFFF;
42 FONT-SIZE: 10pt;
43 }