jQuery实现表格的增、删、改操作示例

这里实现的是在jQuery中通过按钮的形式,对表格进行的一些基本操作,可以实现表格的增删改操作,并实现对鼠标事件监听,实现表格的高亮行操作。

<head> <meta charset="UTF-8"> <title> jQuery表格操作</title> <script src="https://libs.baidu.com/jquery/2.0.0/jquery.min.js"></script> <script type="text/javascript"> $(document).ready(function() { //添加一行 $("#one").click(function() { var $td = $("#trOne").clone(); $("table").append($td); $("table tr:last").find("input").val(""); }); //删除一行 $("#two").click(function() { $("table tr:not(:first):last").remove(); }); //删除所有行 $("#three").click(function() { /*var len=$("tr").length; for(var i=0;i<=len;i++){ $("tr")[i].remove(); }*/ //除第一行为其它行删除 $("tr:not(:first)").remove(); }); //删除选中的行 $("#four").click(function() { //遍历选中的checkbox $("[type='checkbox']:checked").each(function() { //获取checkbox所在行的顺序 n = $(this).parents("tr").index(); $("table").find("tr:eq(" + n + ")").remove(); }); }); //设置高亮行 $("tr").mouseover(function() { $(this).css("background-color","red"); }); $("tr").mouseout(function(){ $(this).css("background-color","white"); }); }); </script> </head> <body> <input type="button" value="添加一行" /><br /> <input type="button" value="删除一行" /><br /> <input type="button" value="删除所有行" /><br /> <input type="button" value="删除选中的行" /><br /> <table cellspacing="0" cellpadding="0"> <tr> <td><input type="checkbox"></td> <td><input type="" value="姓名" </td> <td><input type="" value="年龄" </td> <td><input type="" value="性别" </td> </tr> <tr> <td><input type="checkbox"></td> <td><input type="" value="张三" </td> <td><input type="" value="18" </td> <td><input type="" value="男" </td> </tr> <tr> <td><input type="checkbox"></td> <td><input type="" value="李四" </td> <td><input type="" value="18" </td> <td><input type="" value="男" </td> </tr> <tr> <td><input type="checkbox"></td> <td><input type="" value="王五" </td> <td><input type="" value="18" </td> <td><input type="" value="男" </td> </tr> </table> </body>

效果图如下:

jQuery实现表格的增、删、改操作示例

感兴趣的朋友可以使用在线HTML/CSS/JavaScript代码运行工具测试上述代码运行效果。

更多关于jQuery相关内容感兴趣的读者可查看本站专题:《jQuery表格(table)操作技巧汇总》、《jQuery操作xml技巧总结》、《jQuery form操作技巧汇总》、《jQuery常用插件及用法总结》、《jQuery扩展技巧总结》及《jquery选择器用法总结

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:http://www.heiqu.com/72429d5a718df102846b143549198f1e.html