我发现了一个很棒的 jQuery 片段,它允许将选项从一个选择器复制到另一个选择器并返回。
我想修改它以添加选项组,并且当所有选项从一侧移动到另一侧时,将选项组从空组中删除并将其添加到新选择器中的完整组中。
仅仅使用 jQuery 就能完成类似的事情吗?
HTML:
<select multiple id="select1" class="w100p">
<optgroup label="Group 1">
<option value="1">Option 1a</option>
<option value="2">Option 1b</option>
</optgroup>
<optgroup label="Group 2">
<option value="3">Option 2a</option>
<option value="4">Option 2b</option>
</optgroup>
</select>
<a href="#" id="add">add >></a>
<br>
<a href="#" id="remove"><< remove</a>
<select multiple id="select2" class="w100p"></select>
JavaScript:
$('#add').click(function() {
return !$('#select1 option:selected').remove().appendTo('#select2');
});
$('#remove').click(function() {
return !$('#select2 option:selected').remove().appendTo('#select1');
});
最佳答案
尽管这并不完美,但它应该可以帮助您入门:
var $select1 = $('#select1');
$select2 = $('#select2');
$('option').each(function(){
$(this).data('optgroup', $(this).parent().attr('label'));
});
$('#add').click(function() {
var $el = $('#select1 option:selected'),
groupName = $el.data('optgroup'),
$parent = $el.parent(),
$optgroup = $select2.find('optgroup[label="' + groupName + '"]');
if ( ! $el.length ) return false;
if ( ! $optgroup.length ) $optgroup = $('<optgroup label="' + $el.data('optgroup') + '" />').appendTo($select2);
$el.appendTo( $optgroup );
if ( ! $parent.children().length ) $parent.remove();
return false;
});
$('#remove').click(function() {
var $el = $('#select2 option:selected'),
groupName = $el.data('optgroup'),
$parent = $el.parent(),
$optgroup = $select1.find('optgroup[label="' + groupName + '"]');
if ( ! $el.length ) return false;
if ( ! $optgroup.length ) $optgroup = $('<optgroup label="' + $el.data('optgroup') + '" />').appendTo($select1);
$el.appendTo( $optgroup );
if ( ! $parent.children().length ) $parent.remove();
return false;
});
就像我说的,它需要一些额外的工作(例如合并两个功能;它们基本上做同样的事情),但应该可以帮助您开始。
最后,这是 fiddle :http://jsfiddle.net/m97zR/3/
关于jquery - 使用 jQuery 复制选项和选项组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7717597/