How do I move list items?

前端 未结 3 586
终归单人心
终归单人心 2021-02-08 03:45

I have a normal unordered list

  • Item 1
  • Item 2
  • Item 3
  • Item 4
相关标签:
3条回答
  • 2021-02-08 04:24

    Add an id to the unordered list (<ul id="list">), and add it after the second child.

    $('#list li').click(function() {
        $(this).insertAfter("#list li:nth-child(1)");
    });
    

    This only works for elements after the first, but an example is on jsFiddle.

    0 讨论(0)
  • 2021-02-08 04:29

    Take a look at nth selector here http://api.jquery.com/nth-child-selector/ it could help you.

    0 讨论(0)
  • 2021-02-08 04:40

    This does everything but the animation:

    $('li').click(function() {
        var $this = $(this);
        $this.insertAfter($this.siblings(':eq(0)'));
    });
    

    When you click on a list item, it will insert it after the first item in the <ul>, i.e. the second position in the list.

    Furthermore, you could animate this in various ways. Here's one:

    $('li').click(function() {
        var $this = $(this),
            callback = function() {
                $this.insertAfter($this.siblings(':eq(0)'));
            };
        $this.slideUp(500, callback).slideDown(500);
    });
    

    Here's a working demo.

    0 讨论(0)
提交回复
热议问题