JQuery动态给table添加、删除行
最近需要使用JQuery动态操作table,自己整理了一下,可以添加新行,删除选中的一行或多行,简单代码如下:
1 <html>
2 <head>
3 <title>
4 </title>
5 <script src="js/jquery-1.4.2_min.js" type="text/javascript"></script>
6 <script type="text/javascript" language="javascript">
7 var row_count = 0;
8 function addNew()
9 {
10 var table1 = $('#table1');
11 var firstTr = table1.find('tbody>tr:first');
12 var row = $("<tr></tr>");
13 var td = $("<td></td>");
14 td.append($("<input type='checkbox' name='count' value='New'><b>CheckBox"+row_count+"</b>")
15 );
16 row.append(td);
17 table1.append(row);
18 row_count++;
19 }
20 function del()
21 {
22 var checked = $("input[type='checkbox'][name='count']");
23 $(checked).each(function(){
24 if($(this).attr("checked")==true) //注意:此处判断不能用$(this).attr("checked")==‘true’来判断。
25 {
26 $(this).parent().parent().remove();
27 }
28 });
29 }
30 </script>
31 </head>
32 <body>
33 <input type="button" value="Add" onclick="addNew();">
34 <input type="button" value="Delete" onclick="del();">
35 <div id="rightcontent">
36 <table id="table1" cellspacing="3" cellpadding="3" border="1">
37 <tbody>
38 <tr>
39 <th>
40 Add new row,then test the delete function.
41 </th>
42 </tr>
43 </tbody>
44 </table>
45 </div>
46 </body>
47 </html>
2 <head>
3 <title>
4 </title>
5 <script src="js/jquery-1.4.2_min.js" type="text/javascript"></script>
6 <script type="text/javascript" language="javascript">
7 var row_count = 0;
8 function addNew()
9 {
10 var table1 = $('#table1');
11 var firstTr = table1.find('tbody>tr:first');
12 var row = $("<tr></tr>");
13 var td = $("<td></td>");
14 td.append($("<input type='checkbox' name='count' value='New'><b>CheckBox"+row_count+"</b>")
15 );
16 row.append(td);
17 table1.append(row);
18 row_count++;
19 }
20 function del()
21 {
22 var checked = $("input[type='checkbox'][name='count']");
23 $(checked).each(function(){
24 if($(this).attr("checked")==true) //注意:此处判断不能用$(this).attr("checked")==‘true’来判断。
25 {
26 $(this).parent().parent().remove();
27 }
28 });
29 }
30 </script>
31 </head>
32 <body>
33 <input type="button" value="Add" onclick="addNew();">
34 <input type="button" value="Delete" onclick="del();">
35 <div id="rightcontent">
36 <table id="table1" cellspacing="3" cellpadding="3" border="1">
37 <tbody>
38 <tr>
39 <th>
40 Add new row,then test the delete function.
41 </th>
42 </tr>
43 </tbody>
44 </table>
45 </div>
46 </body>
47 </html>