2016-05-17 87 views
1

我有jQuery代碼中的下列代碼,在列表中向上或向下按鈕上下移動列表項目。無法在jQuery中向上或向下移動列表中的多個項目

  $("#btn-move-up").click(function() { 
      $item = $(".highlight"); 
      $before = $item.prev(); 
      $item.insertBefore($before); 
     }); 

    //onclick of move down button, move the item down in the list 
     $("#btn-move-down").click(function() { 
      $item = $(".highlight"); 
      $after = $item.next(); 
      $item.insertAfter($after); 
     }); 

代碼工作的罰款單項目,但如果您選擇多個項目,它開始表現unexpectedly.the working fiddle here。 有人可以指出我的代碼或其他更好的解決方案中的錯誤嗎?

回答

1

在插入之前需要選擇列表中的第一個項目,插入之前需要選擇最後一個項目。否則,或者爲每個項目後強調之前它會插入:

$("#btn-move-up").click(function() { 
 
    $item = $(".highlight"); 
 
    $before = $item.first().prev(); 
 
    $item.insertBefore($before); 
 
}); 
 

 
//onclick of move down button, move the item down in the list 
 
$("#btn-move-down").click(function() { 
 
    $item = $(".highlight"); 
 
    $after = $item.last().next(); 
 
    $item.insertAfter($after); 
 
}); 
 

 

 
$('ul').on("click", "li", function(e) { 
 
    if ($(this).hasClass('highlight')) { 
 
    $(this).removeClass('highlight'); 
 
    } else { 
 

 
    $(this).addClass('highlight'); 
 

 
    } 
 
    e.stopPropagation(); 
 
});
.highlight { 
 
    background-color: #ccc; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<button type="button" id="btn-move-up" class="btn btn-info" data-toggle="tooltip" data-placement="right" title="Up"><i class="fa fa-arrow-up"></i>Up</button> 
 

 
<button type="button" id="btn-move-down" class="btn btn-info" data-toggle="tooltip" data-placement="right" title="Down"><i class="fa fa-arrow-down"></i>Down</button> 
 

 
<ul id="fields"> 
 
    <li>Ist</li> 
 
    <li>2nd</li> 
 
    <li>3rd</li> 
 
    <li>4th</li> 
 
</ul>

+0

Thanku @Fabricator它的工作。 –

相關問題