Can I use jQuery to easily shift li elements up or down?

前端 未结 3 1858
小鲜肉
小鲜肉 2020-12-15 11:05

I have a menu like this:

    
  • Home
3条回答
  •  [愿得一人]
    2020-12-15 11:39

    It's actually not that hard. JQuery almost gets you there by itself with the insertBefore and insertAfter methods.

    function moveUp($item) {
        $before = $item.prev();
        $item.insertBefore($before);
    }
    
    function moveDown($item) {
        $after = $item.next();
        $item.insertAfter($after);
    }
    

    You could use these like

    moveDown($('#menuAbout'));
    

    and the menuAbout item would move down.

    If you wanted to extend jQuery to include these methods, you would write it like this:

    $.fn.moveUp = function() {
        before = $(this).prev();
        $(this).insertBefore(before);
    };
    
    $.fn.moveDown = function() {
        after = $(this).next();
        $(this).insertAfter(after);
    };
    

    and now you can call the functions like

    $("#menuAbout").moveDown();
    

提交回复
热议问题