1

このコードは機能していますが、アイテムを移動するとリストの一番下に表示されます。順番はアルファベット順にしたいのですが、どこから始めればよいかわかりません。

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<title>demo</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.0/jquery.min.js"></script>

<style type='text/css'>
.whatever {
    width:200px;
    height:50px;
    overflow:auto
}
</style>
<script type='text/javascript'>//<![CDATA[ 
    $(window).load(function(){
    $('#select1').click(function(){
    $('#select1 option:selected').appendTo('#select2');
});

$('#select2').click(function(){
    $('#select2 option:selected').appendTo('#select1');
});

$('#select3').click(function(){
    $('#select3 option:selected').appendTo('#select4');
});

$('#select4').click(function(){
    $('#select4 option:selected').appendTo('#select3');
});
});//]]>  
</script>
</head>
<body>
<div>
<select multiple id="select1" class="whatever">
    <option value="1">Option 1</option>
    <option value="2">Option 2</option>
    <option value="3">Option 3</option>
    <option value="4">Option 4</option>
</select>
<img src="../Common/MultiSelect/img/switch.png">
<select multiple id="select2" class="whatever"></select>
</div>

<div>
<select multiple id="select3" class="whatever">
    <option value="1">Option 1</option>
    <option value="2">Option 2</option>
    <option value="3">Option 3</option>
    <option value="4">Option 4</option>
</select>
<img src="../Common/MultiSelect/img/switch.png">
<select multiple id="select4" class="whatever"></select>
</div>
</body>
</html>
4

1 に答える 1

2

sort メソッドを使用して、必要な順序を維持できます

例 オプション値でソート

 youroptions.sort(function(a,b){
       return a.value - b.value;
 });

兄弟を使用して親div内の兄弟として相対的な選択要素がある場合、コードをかなり短縮できます

$(document).ready(function() {
    $('select').change(function() {
        var $this = $(this);
        $this.siblings('select').append($this.find('option:selected')); // append selected option to sibling
        $('select', $this.parent()).each(function(i,v){ // loop through relative selects
            var $options = $(v).find('option'); // get all options
            $options = $options.sort(function(a,b){ // sort by value of options
                return a.value - b.value;
            });
            $(this).html($options); // add new sorted options to select
        });
    });   
});​

http://jsfiddle.net/e6Y7J/

于 2012-10-03T16:40:29.227 に答える