CODE-用jQuery實作<select>選項上下移動(複選版)
91哥在留言裡出了個jQuery考題:
清單的項目有1,2,3,4,5,單選上下都沒問題了。
多選OK的情況:
(A) 選了2,3,按上,清單會變成2,3,1,4,5。
(B) 選了1,3,按上,清單會變成1,3,2,4,5。
(C) 選了2,5,按上,清單會變成2,1,3,5,4。
小的現在碰到的情況是:
選了1,2,按上,清單會變成2,1,3,4,5。原因是因為 each會從依序從最前面開始判斷,當1不做事時,下一個2則會跟1換位置,需求應該是「選了1,2,按上,清單仍維持1,2,3,4,5」。
不曉得針對這樣的需求,黑大有沒建議的作法?
好一個難易適中的挑戰題,忍不住手癢,就試解如下: (程式行數較單選版稍有增加,但仍維持jQuery慣有的簡潔性。)
<html>
<head>
<script type='text/javascript' src='http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.js'></script>
<script type='text/javascript'>
$(function() {
//宣告jQuery陣列逆轉函數, 這是網路上找到的寫法
//借了Array.reverse的native function來用(哇哩咧,這樣也行)
$.fn.reverse = [].reverse;
$("#bUp,#bDown").click(function() {
var $opt = $("#selList option:selected");
if (!$opt.length) return;
var bGoUp = (this.id == "bUp");
//向下移時, 逆轉結果陣列,由下往上做
if (!bGoUp) $opt.reverse();
$opt.each(function(i) {
var $src = $(this);
var $dst = $src[bGoUp ? "prev" : "next"]();
//移動對象若也被選取,則不動
if ($dst.length && $dst[0].selected) return;
$dst[bGoUp ? "before" : "after"]($src);
});
});
});
</script>
</head><body>
<select id='selList' size='7' style='width: 100px' multiple>
<option>Item 1</option>
<option>Item 2</option>
<option>Item 3</option>
<option>Item 4</option>
<option>Item 5</option>
</select><br />
<input type="button" id="bUp" value="Up" />
<input type="button" id="bDown" value="Down" />
</body>
</html>