jquery的table操作之在指定行后添加新行

View Code
 1 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">  
 2 <HTML>  
 3 <HEAD>  
 4 <TITLE> New Document </TITLE>  
 5 <META NAME="Generator" CONTENT="EditPlus">  
 6 <META NAME="Author" CONTENT="">  
 7 <META NAME="Keywords" CONTENT="">  
 8 <META NAME="Description" CONTENT="">  
 9 <script src="style/lib/jquery.js"></script>  
10 <script>  
11   
12    //注意input的id和tr的id要一样  
13    function addRowByID(currentRowID){  
14        //遍历每一行,找到指定id的行的位置i,然后在该行后添加新行  
15        $.each( $('table:first tbody tr'), function(i, tr){  
16            if($(this).attr('id')==currentRowID){  
17                //获取当前行  
18                var currentRow=$('table:first tbody tr:eq('+i+')');  
19                //要添加的行的id  
20                var addRowID=currentRowID+1;  
21                str = "<tr id = '"+addRowID+"'><td>"+addRowID+"</td><td>row"+addRowID+"</td>"+  
22                "<td><input id= '"+addRowID+"' type='button' value='添加行' onclick='addRowByID(this.id);' /></td></tr>";  
23                //当前行之后插入一行  
24                currentRow.after(str);  
25            }  
26        });  
27    }  
28 </script>  
29 </HEAD>  
30   
31 <BODY>  
32    <table border="1" bordercolor="green">  
33        <thead>  
34            <tr>  
35                <th>id</th>  
36                <th>value</th>  
37                <th>button</th>  
38            </tr>  
39        </thead>  
40        <tbody>  
41            <!-- 这里是input的id和tr的id要一样 -->  
42            <tr id='aaa'>  
43                <td>0</td>  
44                <td>row0</td>  
45                <td><input id='aaa' type="button" value="添加行" onclick="addRowByID(this.id);" /></td>  
46            </tr>  
47            <tr id='bbb'>  
48                <td>1</td>  
49                <td>row1</td>  
50                <td><input id='bbb' type="button" value="添加行" onclick="addRowByID(this.id);" /></td>  
51            </tr>  
52            <tr id='ccc'>  
53                <td>2</td>  
54                <td>row2</td>  
55                <td><input id='ccc' type="button" value="添加行" onclick="addRowByID(this.id);" /></td>  
56            </tr>  
57        </tbody>  
58    </table>  
59 </BODY>  
60 </HTML> 
原文地址:https://www.cnblogs.com/weixing/p/2995282.html