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>
以上就是本文的全部內容,希望對大傢的學習有所幫助,也希望大傢多多支持WalkonNet。