我有这个代码正在运行但是当项目被移动时,它会显示在列表的底部。我更喜欢按字母顺序保留订单,不知道从哪里开始。
<!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>
答案 0 :(得分:2)
您可以使用排序方法来保持您想要的顺序
示例按您的选项值排序
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
});
});
});