JQuery实现表格数据行上移与下移
本文实例为大家分享了JQuery实现表格数据行上移与下移的具体代码,供大家参考,具体内容如下
效果展示
代码实现
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Bootstrap 实例 - 条纹表格</title> <link rel="stylesheet" href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css"> <script src="https://cdn.bootcss.com/jquery/2.1.1/jquery.min.js"></script> <script src="https://cdn.bootcss.com/bootstrap/3.3.7/js/bootstrap.min.js"></script> <style type="text/css"> .moveUpOrDown { background-color: #5BC0DE; border-radius: 3px; cursor: pointer; color: #FFFFFF; padding: 2px; font-size: 12px; } </style> <script type="text/javascript"> $(function () { /** * 为 上移 、下移 按钮绑定点击事件 */ $("body").on("click", ".moveUpOrDown", function () { var text = $(this).text(); if (text == "上移") { var prevTr = $(this).parent().parent().prevAll(); /**如果当前行不是第一行,则上移它*/ if (prevTr.length > 0) { var preTemp = prevTr.first(); var thisHr = $(this).parent().parent(); /**将上一行与本行交互内容,replaceWith 方法内容为 html 内容 * 可参考文档:http://www.w3school.com.cn/jquery/manipulation_replacewith.asp*/ thisHr.replaceWith("<tr>" + preTemp.html() + "</tr>"); preTemp.replaceWith("<tr>" + thisHr.html() + "</tr>"); } } else if (text == "下移") { var nextTr = $(this).parent().parent().next(); if (nextTr.length > 0) { var thisHr = $(this).parent().parent(); /**将本行与下一行交互内容,replaceWith 方法内容为 html 内容 */ thisHr.replaceWith("<tr>" + nextTr.html() + "</tr>"); nextTr.replaceWith("<tr>" + thisHr.html() + "</tr>"); } } }); }); </script> </head> <body> <table class="table table-striped"> <caption>条纹表格布局</caption> <thead> <tr> <th>名称</th> <th>城市</th> <th>邮编</th> <th>排序</th> </tr> </thead> <tbody> <tr> <td>Tanmay1</td> <td>Bangalore</td> <td>560001</td> <td><span class="moveUpOrDown">上移</span> | <span class="moveUpOrDown">下移</span></td> </tr> <tr> <td>Sachin1</td> <td>Mumbai</td> <td>400003</td> <td><span class="moveUpOrDown">上移</span> | <span class="moveUpOrDown">下移</span></td> </tr> <tr> <td>Uma1</td> <td>Pune</td> <td>411027</td> <td><span class="moveUpOrDown">上移</span> | <span class="moveUpOrDown">下移</span></td> </tr> <tr> <td>Tanmay2</td> <td>Bangalore</td> <td>560001</td> <td><span class="moveUpOrDown">上移</span> | <span class="moveUpOrDown">下移</span></td> </tr> <tr> <td>Sachin2</td> <td>Mumbai</td> <td>400003</td> <td><span class="moveUpOrDown">上移</span> | <span class="moveUpOrDown">下移</span></td> </tr> <tr> <td>Uma2</td> <td>Pune</td> <td>411027</td> <td><span class="moveUpOrDown">上移</span> | <span class="moveUpOrDown">下移</span></td> </tr> <tr> <td>Tanmay3</td> <td>Bangalore</td> <td>560001</td> <td><span class="moveUpOrDown">上移</span> | <span class="moveUpOrDown">下移</span></td> </tr> <tr> <td>Sachin3</td> <td>Mumbai</td> <td>400003</td> <td><span class="moveUpOrDown">上移</span> | <span class="moveUpOrDown">下移</span></td> </tr> <tr> <td>Uma3</td> <td>Pune</td> <td>411027</td> <td><span class="moveUpOrDown">上移</span> | <span class="moveUpOrDown">下移</span></td> </tr> </tbody> </table> </body> </html>
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持我们。
赞 (0)