jQuery将项目从一个选择框移动到另一个选择框,同时保留列表顺序
我有这个代码正在工作,但当项目被移动时,它显示在列表的底部。 我更喜欢按字母顺序保留订单,不知道从哪里开始。
demo .whatever { width:200px; height:50px; overflow:auto } // Option 1 Option 2 Option 3 Option 4 Option 1 Option 2 Option 3 Option 4
您可以使用排序方法来保持所需的顺序
示例按选项值排序
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 }); }); });