本来想写一个 JQuery 操作 table 的例子,结果发现网上有很多写的更好的,推荐这个博主写的文章:
https://www.cnblogs.com/lxblog/archive/2013/01/11/2856582.html
相比之下,自己写的例子相形见绌。
这里也将自己的例子写在下面,方便寻找对 table 增加删除列的朋友查看参考。
代码如下:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>JQuery操作table</title> <script src="http://code.jquery.com/jquery-latest.js"></script> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous"> </head> <body> <table id="fineTable" class="table table-hover" style="margin-top: 80px; "> <tr> <td style="text-align: center; font-weight: bold; ">被罚人</td> <td style="text-align: center; font-weight: bold; ">被罚金额</td> <td style="text-align: center; font-weight: bold; ">是否管理人员</td> <td width="100px; " style="text-align: center; "><button type="button" class="btn btn-info btn-xs" onclick="addTr(oneTr())">添加一行</button></td> </tr> <tr> <td style="text-align: center; "> <input type="text" name="beFinedMan" value="" > </td> <td style="text-align: center; "> <input type="text" name="fineMoney" value="" /> </td> <td style="text-align: center; "> <label><input type="radio" name="flag" value="0" />是</label> <label><input type="radio" name="flag" value="1" />否</label> </td> <td style="text-align: center; "><button type="button" class="btn btn-danger btn-xs" onclick="delTr(this)">删除一行</button></td> </tr> </table> </body> <script> /**下面是操作表格的方法*/ /** * 为table指定行添加一行 * table的行从0开始 * trHtml 添加行的html代码 */ function addTr(trHtml){ //获取table最后一行 $("#fineTable tr:last") //获取table第一行 $("#fineTable tr").eq(0) //获取table倒数第二行 $("#fineTable tr").eq(-2) var $tr = $("#fineTable tr:last"); if($tr.size()==0){ alert("指定的table或对应的行数不存在!"); return; } $tr.after(trHtml); } /**删除一行*/ function delTr($this){ $($this).parent().parent().remove(); } /**生成一行 * 这一行的写法就是:先写一个 return '',然后将 <tr>......</tr> 一个 tr 中的内容直接复制过来即可。注意每个 tr 都应该带上对应的方法 */ function oneTr(){ return '<tr>\n' + ' <td style="text-align: center; ">\n' + ' <input type="text" name="beFinedMan" value="" >\n' + ' </td>\n' + ' <td style="text-align: center; ">\n' + ' <input type="text" name="fineMoney" value="" />\n' + ' </td>\n' + ' <td style="text-align: center; ">\n' + ' <label><input type="radio" name="flag" value="0" />是</label>\n' + ' <label><input type="radio" name="flag" value="1" />否</label>\n' + ' </td>\n' + ' <td style="text-align: center; "><button type="button" class="btn btn-danger btn-xs" onclick="delTr(this)">删除一行</button></td>\n' + ' </tr>'; } </script> </body> </html>
运行截图:
需要注意的是,this 可以作为参数传入,但是不能作为变量名。比如,如果 delTr() 方法写成下面所示的代码,该方法将会无效:
错误示例:
/**错误示例*/ /**删除一行*/ function delTr(this){ $(this).parent().parent().remove(); }