7

Need to change li position by clicking to move up or to move down.

<div>
  <ul>
    <li>Item1  <a class="moveUp">Move Up</a> <a class="moveDown">Move Down</a></li>
    <li>Item2  <a class="moveUp">Move Up</a> <a class="moveDown">Move Down</a></li>
    <li>Item3  <a class="moveUp">Move Up</a> <a class="moveDown">Move Down</a></li>
    <li>Item4  <a class="moveUp">Move Up</a> <a class="moveDown">Move Down</a></li>
    <li>Item5  <a class="moveUp">Move Up</a> <a class="moveDown">Move Down</a></li>
  </ul>
</div>

So what should happen here, for example, if we click Move up on Item2, the Item 2 will move up before Item 1.

I tryed to do like this, but it doesn't work:

$(".moveUp").click(function () {
    var thisLine = $(this).parent();
    var prevLine = thisLine.prev();
    prevLine.insertAfter(thisLine);
});

Hope some one can help me...

4

5 回答 5

6

尝试这个:

$(".moveUp").click(function () {
    var thisLine = $(this).parent();
    var prevLine = thisLine.prev();
    prevLine.before(thisLine);
});

$(".moveDown").click(function () {
    var thisLine = $(this).parent();
    var prevLine = thisLine.next();
    prevLine.after(thisLine);
});

在这里工作 jsFiddle 。

于 2012-04-04T15:55:44.003 回答
3

尝试这个。

$(".moveUp").click(function () {
    var $parent = $(this).parent();
    $parent.prev().before($parent);
});
$(".moveDown").click(function () {
    var $parent = $(this).parent();
    $parent.next().after($parent);
});

工作演示 - http://jsfiddle.net/vQmHU/

于 2012-04-04T15:56:31.553 回答
2

这应该有效,并且当您尝试在顶部向上或在底部向下移动元素时,也不会将元素移动到 UL 之外:

$('.moveUp').click(function(){
    var liItem = $(this).parent();
    if (liItem.prev().is('li'))
    {
        liItem.insertBefore(liItem.prev())
    }
});

$('.moveDown').click(function(){
    var liItem = $(this).parent();
    if (liItem.next().is('li'))
    {
        liItem.insertAfter(liItem.next())
    }
});

工作示例:http: //jsfiddle.net/BDecp/

此外,您的代码应该用这个包装:

$(document).ready(function () {
    //Code Here
});
于 2012-04-04T16:12:18.537 回答
1

这仅重新排列列表项:

$(".moveUp").click(function () {
  var $parent = $(this).parent().closest("li");
  $parent.prev().before($parent);
});

$(".moveDown").click(function () {
  var $parent = $(this).parent().closest("li");
  $parent.next().after($parent);
});
于 2012-09-14T16:05:35.507 回答
0

http://jsfiddle.net/j7xtS/2/

$('ul').on('click', 'a', function(){
    var $this = $(this),
        $li = $this.parent();

    if ($this.hasClass('moveUp') &&  $li.prev().length>0){
        $li.prev().before($li[0]);
    }
    else if ($this.hasClass('moveDown') && $li.next().length>0){
        $li.next().after($li[0]);
    }
});​
于 2012-04-04T16:08:41.143 回答