DIV CSS 佈局教程網

用 jQuery 實作清單項目的上下移動
編輯:JQuery特效代碼     

讓使用者調整清單順序,除了表格,也可以用在 div 或 li 組成的卡片清單上。核心邏輯與表格版一樣:找到目前元素,跟它的兄弟交換位置。

程式碼

$(this).ready(function() {

    // 上移:往上交換
    $(".up").each(function() {
        $(this).click(function() {
            var $tr = $(this).parents("li");
            if ($tr.index() != 0) {          // 不是第一項才移
                $tr.prev().before($tr);
            }
        });
    });

    // 下移:往下交換
    var trLength = $(".down").length;
    $(".down").each(function() {
        $(this).click(function() {
            var $tr = $(this).parents("li");
            if ($tr.index() != trLength) {
                $tr.next().after($tr);
            }
        });
    });

    // 以核取方塊選取後,用連結批次移動
    $("a[name='up']").click(function() {
        if ($("input[name='rule']:checked").size() > 1) {
            alert("只能選擇一項進行上下移操作!");
            return;
        }
        $("input[name='rule']:checked").each(function() {
            var $div = $('#rule_' + $(this).val());
            if ($div.index() != 0) {
                $div.prev().before($div);
            }
        });
    });

    $("a[name='down']").click(function() {
        if ($("input[name='rule']:checked").size() > 1) {
            alert("只能選擇一項進行上下移操作!");
            return;
        }
        $("input[name='rule']:checked").each(function() {
            var $div = $('#rule_' + $(this).val());
            if ($('#rule_' + (parseInt($(this).val()) + 1)).html() != null) {
                $div.next().after($div);
            }
        });
    });
});

核心技巧只有兩行

$el.prev().before($el) 與 $el.next().after($el)。前者把目前元素插到上一個兄弟之前,後者插到下一個兄弟之後。因為 jQuery 的 DOM 操作是「搬移」而非複製,這一組組合就能完成交換。

這份程式碼的幾個問題

1. $(this).ready() 是錯的。 ready 應該綁在 document 上,寫成 $(function(){ ... }) 或 $(document).ready(...)。對任意元素呼叫 .ready() 在 jQuery 3 中已被移除。

2. .parents() 應改用 .closest()。 parents() 會回傳所有符合條件的祖先(可能好幾層),closest() 只回傳最近的那一個。這裡要的是所屬的那個 li,用 closest('li') 才正確。

3. 邊界判斷有 bug。 下移時寫 $tr.index() != trLength,但 trLength 是「總數」,而索引最大值是「總數 - 1」。若共有 9 項,最後一項索引為 8,而 trLength 是 9,條件 8 != 9 成立,於是會嘗試對不存在的下一個兄弟做 after()——操作靜默失敗,使用者只看到「按了沒反應」。正確寫法應該用長度比較:

var $items = $('.item');
var $item = $(this).closest('.item');
var idx = $items.index($item);
if (idx > 0)                  { $item.prev().before($item); }   // 上移
if (idx < $items.length - 1) { $item.next().after($item); }    // 下移

4. 用 id 推算下一個元素不可靠。 $('#rule_' + (val + 1)) 假設 id 是連續數字,一旦有刪除就斷了。直接用 $item.next() 判斷是否存在即可,不必繞道 id。

5. .size() 與 <a> 當按鈕。 .size() 已在 jQuery 3 移除,改用 .length;用 <a href="#"> 當動作按鈕,應該改用 <button type="button">,並記得 e.preventDefault()(若堅持用 a)。

整理後的版本

$(function(){
    function move($item, dir){
        var $siblings = $item.parent().children();
        var idx = $siblings.index($item);
        if (dir === 'up'   && idx > 0)                    $item.prev().before($item);
        if (dir === 'down' && idx < $siblings.length - 1) $item.next().after($item);
    }

    $('.item').on('click', '.up',   function(){ move($(this).closest('.item'), 'up'); });
    $('.item').on('click', '.down', function(){ move($(this).closest('.item'), 'down'); });
});

用事件委派綁在容器上,動態新增的項目也自動生效,而且不必為每一項各綁一次。移動後別忘了把新順序存回後端,否則重新整理就會還原。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved