本节书摘来自异步社区《jQuery、jQuery UI及jQuery Mobile技巧与示例》一书中的第3章,第3.13节,作者:【荷】Adriaan de Jonge , 【美】Phil Dutson著,更多章节内容可以访问云栖社区“异步社区”公众号查看
可以使用insertBefore()和insertAfter()向上和向下移动列表中已存在的元素。代码清单3-13演示了如何通过Up和Down按钮移动一列div元素。
代码清单3-13 通过Up和Down按钮更改
列表元素的顺序 00 <!DOCTYPE html> 01 02 <html lang="en"> 03 <head> 04 <title>Pushing elements up and down</title> 05 <style> 06 /* 请将下列代码移至一个外部的 07 .css文件 */ 08 div:first-of-type button.up { 09 visibility: hidden; 10 } 11 div:last-of-type button.down { 12 visibility: hidden; 13 } 14 </style> 15 </head> 16 <body> 17 18 <h2>Click on the up and down buttons to move the rows</h2> 19 20 <div> 21 <button class="up">Up</button> 22 <button class="down">Down</button> 23 This was initially the first element. 24 </div> 25 <div> 26 <button class="up">Up</button> 27 <button class="down">Down</button> 28 This was initially the second element. 29 </div> 30 <div> 31 <button class="up">Up</button> 32 <button class="down">Down</button> 33 This was initially the third element. 34 </div> 35 <div> 36 <button class="up">Up</button> 37 <button class="down">Down</button> 38 This was initially the fourth element. 39 </div> 40 <div> 41 <button class="up">Up</button> 42 <button class="down">Down</button> 43 This was initially the fifth element. 44 </div> 45 46 <script src="http://code.jquery.com/jquery-1.7.2.min.js"></script> 47 48 <script> 49 // 请将下列代码移至一个外部的.js文件中 50 $(document).ready(function() { 51 52 $('.up').click(function() { 53 var parent = $(this).parent(); 54 parent.insertBefore(parent.prev()); 55 }); 56 $('.down').click(function() { 57 var parent = $(this).parent(); 58 parent.insertAfter(parent.next()); 59 }); 60 61 }); 62 </script> 63 </body> 64 </html>使用HTML顶部的CSS样式表隐藏了第一个Up按钮和最后一个Down按钮。调用insertBefore()和insertAfter()会自动把元素从当前位置移走。
相关资源:jQuery.ui.1.7.2中文文档