我很确定错误出在我的 PHP 代码中,因为我认为代码正在为每个选项编写一个 optgroup,因此它正在读取这样的内容<option>option 1</option></optgroup><optgroup><option>option 2</option></optgroup><optgroup><option>option 3</option></optgroup>我的 PHP 代码:<?php $sql = "SELECT * FROM `users`,`departments` WHERE users.dept = Department.dept_name";$query = mysql_query($sql);echo "<select name='test[]' id='optgroup' class='ms' multiple='multiple'>";?><?php while ($row = mysql_fetch_array($query)) {echo "<optgroup label=".$row['dept_name']."><option value=".$row['user_name'].">".$row['user_name']."</option></optgroup>";}?></选择>用户表架构:创建表 users ( `user_id` int(11) NOT NULL AUTO_INCREMENT,`user_role` varchar(255) 非空,`user_name` varchar(255) 非空,`gender` varchar(255) 非空,`dob` varchar(255) 非空,`email` varchar(255) 非空,`address` varchar(255) 非空,`phone` varchar(30) 不为空,`dept` varchar(255) 非空,`username` varchar(255) 非空,`password` varchar(255) 非空,`userpic` varchar(255) 非空,主键(`user_id`)) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=latin1部门表结构:部门创建表`部门`(`dept_id` int(11) NOT NULL AUTO_INCREMENT,`dept_name` varchar(255) 非空,`dept_supervisor` varchar(255) 非空,`dept_desc` varchar(255) 非空,`dept_email` varchar(255) 非空,`dept_phone` varchar(100) 非空,主键(`dept_id`)) ENGINE=InnoDB AUTO_INCREMENT=23 DEFAULT CHARSET=latin1片段:/** 多选 v0.9.12* 版权所有 (c) 2012 Louis Cuny** 该程序是免费软件.它没有任何保证,* 适用法律允许的范围.你可以重新分发它* 和/或根据 Do What The Fuck You Want 的条款修改它* 公共许可证,第 2 版,由 Sam Hocevar 发布.看* http://sam.zoy.org/wtfpl/COPYING 了解更多详情.*/!function ($) {严格使用";/* 多选类定义* ====================== */var MultiSelect = 函数(元素,选项){this.options = 选项;this.$element = $(element);this.$container = $('<div/>', { 'class': "ms-container" });this.$selectableContainer = $('', { 'class': 'ms-selectable' });this.$selectionContainer = $('<div/>', { 'class': 'ms-selection' });this.$selectableUl = $('<ul/>', { 'class': "ms-list", 'tabindex' : '-1' });this.$selectionUl = $('<ul/>', { 'class': "ms-list", 'tabindex': '-1' });this.scrollTo = 0;this.elemsSelector = 'li:visible:not(.ms-optgroup-label,.ms-optgroup-container,.'+options.disabledClass+')';};MultiSelect.prototype = {构造函数:多选,初始化:函数(){var that = this,ms = this.$element;if (ms.next('.ms-container').length === 0){ms.css({ position: 'absolute', left: '-9999px' });ms.attr('id', ms.attr('id') ? ms.attr('id') : Math.ceil(Math.random()*1000)+'multiselect');this.$container.attr('id', 'ms-'+ms.attr('id'));this.$container.addClass(that.options.cssClass);ms.find('option').each(function(){that.generateLisFromOption(this);});this.$selectionUl.find('.ms-optgroup-label').hide();如果(that.options.selectableHeader){that.$selectableContainer.append(that.options.selectableHeader);}that.$selectableContainer.append(that.$selectableUl);如果(that.options.selectableFooter){that.$selectableContainer.append(that.options.selectableFooter);}如果(that.options.selectionHeader){that.$selectionContainer.append(that.options.selectionHeader);}that.$selectionContainer.append(that.$selectionUl);如果(that.options.selectionFooter){that.$selectionContainer.append(that.options.selectionFooter);}that.$container.append(that.$selectableContainer);that.$container.append(that.$selectionContainer);ms.after(that.$container);that.activeMouse(that.$selectableUl);that.activeKeyboard(that.$selectableUl);var action = that.options.dblClick ?'dblclick' : '点击';that.$selectableUl.on(action, '.ms-elem-selectable', function(){that.select($(this).data('ms-value'));});that.$selectionUl.on(action, '.ms-elem-selection', function(){that.deselect($(this).data('ms-value'));});that.activeMouse(that.$selectionUl);that.activeKeyboard(that.$selectionUl);ms.on('焦点', 函数(){that.$selectableUl.focus();});}var selectedValues = ms.find('option:selected').map(function(){ return $(this).val(); }).get();that.select(selectedValues, 'init');if (typeof that.options.afterInit === '函数') {that.options.afterInit.call(this, this.$container);}},'generateLisFromOption':函数(选项,索引,$container){var that = this,ms = that.$element,属性 = "",$option = $(option);for (var cpt = 0; cpt < option.attributes.length; cpt++){var attr = option.attributes[cpt];if(attr.name !== 'value' && attr.name !== 'disabled'){属性 += attr.name+'="'+attr.value+'" ';}}var selectableLi = $('<li'+attributes+'><span>'+that.escapeHTML($option.text())+'</span></li>'),selectedLi = selectableLi.clone(),价值 = $option.val(),elementId = that.sanitize(value);可选Li.data('ms-value', value).addClass('ms-elem-selectable').attr('id', elementId+'-selectable');选择李.data('ms-value', value).addClass('ms-elem-selection').attr('id', elementId+'-selection').隐藏();if ($option.prop('disabled') || ms.prop('disabled')){selectedLi.addClass(that.options.disabledClass);selectableLi.addClass(that.options.disabledClass);}var $optgroup = $option.parent('optgroup');如果($optgroup.length > 0){var optgroupLabel = $optgroup.attr('label'),optgroupId = that.sanitize(optgroupLabel),$selectableOptgroup = that.$selectableUl.find('#optgroup-selectable-'+optgroupId),$selectionOptgroup = that.$selectionUl.find('#optgroup-selection-'+optgroupId);如果($selectableOptgroup.length === 0){var optgroupContainerTpl = '<li class="ms-optgroup-container"></li>',optgroupTpl = '<ul class="ms-optgroup"><li class="ms-optgroup-label"><span>'+optgroupLabel+'</span></li></ul>';$selectableOptgroup = $(optgroupContainerTpl);$selectionOptgroup = $(optgroupContainerTpl);$selectableOptgroup.attr('id', 'optgroup-selectable-'+optgroupId);$selectionOptgroup.attr('id', 'optgroup-selection-'+optgroupId);$selectableOptgroup.append($(optgroupTpl));$selectionOptgroup.append($(optgroupTpl));如果(that.options.selectableOptgroup){$selectableOptgroup.find('.ms-optgroup-label').on('click', function(){var values = $optgroup.children(':not(:selected, :disabled)').map(function(){ return $(this).val();}).get();that.select(values);});$selectionOptgroup.find('.ms-optgroup-label').on('click', function(){var values = $optgroup.children(':selected:not(:disabled)').map(function(){ return $(this).val();}).get();that.deselect(values);});}that.$selectableUl.append($selectableOptgroup);that.$selectionUl.append($selectionOptgroup);}索引 = 索引 === 未定义?$selectableOptgroup.find('ul').children().length : index + 1;selectableLi.insertAt(index, $selectableOptgroup.children());selectedLi.insertAt(index, $selectionOptgroup.children());} 别的 {索引 = 索引 === 未定义?that.$selectableUl.children().length : index;selectableLi.insertAt(index, that.$selectableUl);selectedLi.insertAt(index, that.$selectionUl);}},'addOption':功能(选项){var that = this;if (options.value !== undefined && options.value !== null){选项 = [选项];}$.each(options, function(index, option){if (option.value !== undefined && option.value !== null &&that.$element.find("option[value='"+option.value+"']").length === 0){var $option = $('<option value="'+option.value+'">'+option.text+'</option>'),index = parseInt((typeof option.index === 'undefined' ? that.$element.children().length : option.index)),$container = option.nested === undefined ?that.$element : $("optgroup[label='"+option.nested+"']");$option.insertAt(index, $container);that.generateLisFromOption($option.get(0), index, option.nested);}});},'escapeHTML':函数(文本){返回 $("").text(text).html();},'activeKeyboard' : 函数($list){var that = this;$list.on('焦点', function(){$(this).addClass('ms-focus');}).on('模糊', function(){$(this).removeClass('ms-focus');}).on('keydown', function(e){开关(例如哪个){案例 40:案例 38:e.preventDefault();e.stopPropagation();that.moveHighlight($(this), (e.which === 38) ? -1 : 1);返回;案例 37:案例 39:e.preventDefault();e.stopPropagation();那.switchList($list);返回;案例9:if(that.$element.is('[tabindex]')){e.preventDefault();var tabindex = parseInt(that.$element.attr('tabindex'), 10);tabindex = (e.shiftKey) ?tabindex-1 : tabindex+1;$('[tabindex="'+(tabindex)+'"]').focus();返回;}别的{if(e.shiftKey){that.$element.trigger('focus');}}}if($.inArray(e.which, that.options.keySelect) > -1){e.preventDefault();e.stopPropagation();that.selectHighlighted($list);返回;}});},'moveHighlight': 函数($list, 方向){var $elems = $list.find(this.elemsSelector),$currElem = $elems.filter('.ms-hover'),$nextElem = 空,elemHeight = $elems.first().outerHeight(),容器高度 = $list.height(),containerSelector = '#'+this.$container.prop('id');$elems.removeClass('ms-hover');if (direction === 1){//向下$nextElem = $currElem.nextAll(this.elemsSelector).first();如果($nextElem.length === 0){var $optgroupUl = $currElem.parent();如果 ($optgroupUl.hasClass('ms-optgroup')){var $optgroupLi = $optgroupUl.parent(),$nextOptgroupLi = $optgroupLi.next(':visible');如果($nextOptgroupLi.length > 0){$nextElem = $nextOptgroupLi.find(this.elemsSelector).first();} 别的 {$nextElem = $elems.first();}} 别的 {$nextElem = $elems.first();}}} else if (direction === -1){//向上$nextElem = $currElem.prevAll(this.elemsSelector).first();如果($nextElem.length === 0){var $optgroupUl = $currElem.parent();如果 ($optgroupUl.hasClass('ms-optgroup')){var $optgroupLi = $optgroupUl.parent(),$prevOptgroupLi = $optgroupLi.prev(':visible');如果($prevOptgroupLi.length > 0){$nextElem = $prevOptgroupLi.find(this.elemsSelector).last();} 别的 {$nextElem = $elems.last();}} 别的 {$nextElem = $elems.last();}}}如果($nextElem.length > 0){$nextElem.addClass('ms-hover');var scrollTo = $list.scrollTop() + $nextElem.position().top -容器高度/2 + elemHeight/2;$list.scrollTop(scrollTo);}},'selectHighlighted' : 函数($list){var $elems = $list.find(this.elemsSelector),$highlightedElem = $elems.filter('.ms-hover').first();如果($highlightedElem.length > 0){if ($list.parent().hasClass('ms-selectable')){this.select($highlightedElem.data('ms-value'));} 别的 {this.deselect($highlightedElem.data('ms-value'));}$elems.removeClass('ms-hover');}},'switchList' : 函数($list){$list.blur();this.$container.find(this.elemsSelector).removeClass('ms-hover');if ($list.parent().hasClass('ms-selectable')){this.$selectionUl.focus();} 别的 {this.$selectableUl.focus();}},'activeMouse' : 函数($list){var that = this;this.$container.on('mouseenter', that.elemsSelector, function(){$(this).parents('.ms-container').find(that.elemsSelector).removeClass('ms-hover');$(this).addClass('ms-hover');});this.$container.on('mouseleave', that.elemsSelector, function () {$(this).parents('.ms-container').find(that.elemsSelector).removeClass('ms-hover');});},刷新":函数(){this.destroy();this.$element.multiSelect(this.options);},销毁":函数(){$("#ms-"+this.$element.attr("id")).remove();this.$element.off('焦点');this.$element.css('位置', '').css('left', '');this.$element.removeData('multiselect');},'选择':函数(值,方法){if (typeof value === 'string'){ value = [value];}var that = this,ms = this.$element,msIds = $.map(value, function(val){ return(that.sanitize(val)); }),selectables = this.$selectableUl.find('#' + msIds.join('-selectable, #')+'-selectable').filter(':not(.'+that.options.disabledClass+')'),selections = this.$selectionUl.find('#' + msIds.join('-selection, #') + '-selection').filter(':not(.'+that.options.disabledClass+')'),options = ms.find('option:not(:disabled)').filter(function(){ return($.inArray(this.value, value) > -1); });如果(方法 === 'init'){selectables = this.$selectableUl.find('#' + msIds.join('-selectable, #')+'-selectable'),selections = this.$selectionUl.find('#' + msIds.join('-selection, #') + '-selection');}if (selectables.length > 0){selectables.addClass('ms-selected').hide();selections.addClass('ms-selected').show();options.prop('selected', true);that.$container.find(that.elemsSelector).removeClass('ms-hover');var selectableOptgroups = that.$selectableUl.children('.ms-optgroup-container');如果(selectableOptgroups.length > 0){selectableOptgroups.each(function(){var selectablesLi = $(this).find('.ms-elem-selectable');if (selectablesLi.length === selectablesLi.filter('.ms-selected').length){$(this).find('.ms-optgroup-label').hide();}});var selectionOptgroups = that.$selectionUl.children('.ms-optgroup-container');selectionOptgroups.each(function(){var selectionsLi = $(this).find('.ms-elem-selection');如果 (selectionsLi.filter('.ms-selected').length > 0){$(this).find('.ms-optgroup-label').show();}});} 别的 {if (that.options.keepOrder && method !=='init'){var selectionLiLast = that.$selectionUl.find('.ms-selected');if((selectionLiLast.length > 1) && (selectionLiLast.last().get(0) != selections.get(0))) {selections.insertAfter(selectionLiLast.last());}}}如果(方法!=='初始化'){ms.trigger('改变');if (typeof that.options.afterSelect === 'function') {that.options.afterSelect.call(this, value);}}}},'取消选择':函数(值){if (typeof value === 'string'){ value = [value];}var that = this,ms = this.$element,msIds = $.map(value, function(val){ return(that.sanitize(val)); }),selectables = this.$selectableUl.find('#' + msIds.join('-selectable, #')+'-selectable'),selections = this.$selectionUl.find('#' + msIds.join('-selection, #')+'-selection').filter('.ms-selected').filter(':not(.'+that.options.disabledClass+')'),options = ms.find('option').filter(function(){ return($.inArray(this.value, value) > -1); });如果(选择.长度> 0){selectables.removeClass('ms-selected').show();selections.removeClass('ms-selected').hide();options.prop('selected', false);that.$container.find(that.elemsSelector).removeClass('ms-hover');var selectableOptgroups = that.$selectableUl.children('.ms-optgroup-container');如果(selectableOptgroups.length > 0){selectableOptgroups.each(function(){var selectablesLi = $(this).find('.ms-elem-selectable');if (selectablesLi.filter(':not(.ms-selected)').length > 0){$(this).find('.ms-optgroup-label').show();}});var selectionOptgroups = that.$selectionUl.children('.ms-optgroup-container');selectionOptgroups.each(function(){var selectionsLi = $(this).find('.ms-elem-selection');if (selectionsLi.filter('.ms-selected').length === 0){$(this).find('.ms-optgroup-label').hide();}});}ms.trigger('改变');if (typeof that.options.afterDeselect === 'function') {that.options.afterDeselect.call(this, value);}}},'select_all':函数(){var ms = this.$element,值 = ms.val();ms.find('option:not(":disabled")').prop('selected', true);this.$selectableUl.find('.ms-elem-selectable').filter(':not(.'+this.options.disabledClass+')').addClass('ms-selected').hide();this.$selectionUl.find('.ms-optgroup-label').show();this.$selectableUl.find('.ms-optgroup-label').hide();this.$selectionUl.find('.ms-elem-selection').filter(':not(.'+this.options.disabledClass+')').addClass('ms-selected').show();this.$selectionUl.focus();ms.trigger('改变');if (typeof this.options.afterSelect === '函数') {var selectedValues = $.grep(ms.val(), function(item){返回 $.inArray(item, values) <0;});this.options.afterSelect.call(this, selectedValues);}},'deselect_all':函数(){var ms = this.$element,值 = ms.val();ms.find('option').prop('selected', false);this.$selectableUl.find('.ms-elem-selectable').removeClass('ms-selected').show();this.$selectionUl.find('.ms-optgroup-label').hide();this.$selectableUl.find('.ms-optgroup-label').show();this.$selectionUl.find('.ms-elem-selection').removeClass('ms-selected').hide();this.$selectableUl.focus();ms.trigger('改变');if (typeof this.options.afterDeselect === 'function') {this.options.afterDeselect.call(this, values);}},消毒:功能(值){var hash = 0, i, 字符;if (value.length == 0) 返回哈希值;无功 ls = 0;for (i = 0, ls = value.length; i .ms-container{背景:透明 url('../img/switch.png') 不重复 50% 50%;宽度:370px;}.ms 容器:之后{内容: ".";显示:块;高度:0;行高:0;字体大小:0;清楚:两者;最小高度:0;可见性:隐藏;}.ms-container .ms-selectable, .ms-container .ms-selection{背景:#fff;颜色:#555555;向左飘浮;宽度:45%;}.ms-容器 .ms-选择{浮动:对;}.ms-容器 .ms-list{-webkit-box-shadow: 插入 0 1px 1px rgba(0, 0, 0, 0.075);-moz-box-shadow: 插入 0 1px 1px rgba(0, 0, 0, 0.075);box-shadow: 插入 0 1px 1px rgba(0, 0, 0, 0.075);-webkit-transition:边框线性0.2s,框阴影线性0.2s;-moz-transition:边框线性0.2s,框阴影线性0.2s;-ms-transition:边框线性0.2s,框阴影线性0.2s;-o-transition:边界线性0.2s,框阴影线性0.2s;过渡:边框线性0.2s,框阴影线性0.2s;边框:1px 实心 #ccc;-webkit-border-radius: 3px;-moz-border-radius: 3px;边框半径:3px;位置:相对;高度:200px;填充:0;溢出-y:自动;}.ms-容器 .ms-list.ms-focus{边框颜色:rgba(82, 168, 236, 0.8);-webkit-box-shadow: 插入 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 8px rgba(82, 168, 236, 0.6);-moz-box-shadow: 插入 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 8px rgba(82, 168, 236, 0.6);box-shadow: 插入 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 8px rgba(82, 168, 236, 0.6);大纲:0;轮廓:细虚线\9;}.ms 容器 ul{边距:0;列表样式类型:无;填充:0;}.ms-容器 .ms-optgroup-容器{宽度:100%;}.ms-容器 .ms-optgroup-label{边距:0;填充:5px 0px 0px 5px;光标:指针;颜色:#999;}.ms-container .ms-selectable li.ms-elem-selectable,.ms-container .ms-selection li.ms-elem-selection{边框底部:1px #eee 实心;填充:2px 10px;颜色:#555;字体大小:14px;}.ms-container .ms-selectable li.ms-hover,.ms-container .ms-selection li.ms-hover{光标:指针;颜色:#fff;文字装饰:无;背景色:#08c;}.ms-container .ms-selectable li.disabled,.ms-container .ms-selection li.disabled{背景色:#eee;颜色:#aaa;光标:文本;}<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><select id="optgroup" class="ms" multiple="multiple"><optgroup label="部门 1"><option value="employee_1">员工 1</option><option value="employee_2">员工 2</option><option value="employee_3">员工 3</option></optgroup><optgroup label="部门 2"><option value="employee_4">员工 4</option><option value="employee_5">员工 5</option><option value="employee_6">员工 6</option></optgroup></select> 解决方案 你应该先得到部门名称,然后对每个部门执行一个查询:<?phpecho '<select name="test[]" id="optgroup" class="ms" multiple="multiple">';$departments = mysql_query('SELECT DISTINCT dept_name FROM `departments`');while( $row = mysql_fetch_array( $departments ) ){//使用某种字符转义来防止 XSSecho '<optgroup label="', htmlspecialchars( $row['dept_name'] ), '">';$users = mysql_query( sprintf( 'SELECT user_name FROM `users` WHERE users.dept = "%s"', mysql_real_escape_string( $row['dept_name'] ) );while( $user = mysql_fetch_array( $users ) ){echo '',htmlspecialchars( $user['user_name'] ),'</选项>';}回声'</optgroup>';}回声'</选择>';I am having an issue with MYSQL displaying results correctly when I add the php code to the snippet below.When it runs it displays everything correctly except when I click on the <optgroup> it only reads the first <option></option> rather than reading everything in the <optgroup></optgroup> When I try to use GROUP BY in the MYSQL everything is fixed except it only displays a single column from my database rather than everything filtered.I am pretty sure the error is somewhere in my PHP code as I think the code is writing an optgroup for every option so it is reading it something like this<optgroup><option>option 1</option></optgroup><optgroup><option>option 2</option></optgroup><optgroup><option>option 3</option></optgroup>MY PHP code:<?php $sql = "SELECT * FROM `users`,`departments` WHERE users.dept = departments.dept_name";$query = mysql_query($sql); echo "<select name='test[]' id='optgroup' class='ms' multiple='multiple'>";?> <?php while ($row = mysql_fetch_array($query)) { echo "<optgroup label=".$row['dept_name']."> <option value=".$row['user_name'].">".$row['user_name']."</option> </optgroup>";}?></select>USERS TABLE ARCHETICTURE:CREATE TABLE users ( `user_id` int(11) NOT NULL AUTO_INCREMENT, `user_role` varchar(255) NOT NULL, `user_name` varchar(255) NOT NULL, `gender` varchar(255) NOT NULL, `dob` varchar(255) NOT NULL, `email` varchar(255) NOT NULL, `address` varchar(255) NOT NULL, `phone` varchar(30) NOT NULL, `dept` varchar(255) NOT NULL, `username` varchar(255) NOT NULL, `password` varchar(255) NOT NULL, `userpic` varchar(255) NOT NULL, PRIMARY KEY (`user_id`)) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=latin1DEPARTMENTS TABLE ARCHETICTURE:departmentsCREATE TABLE `departments` ( `dept_id` int(11) NOT NULL AUTO_INCREMENT, `dept_name` varchar(255) NOT NULL, `dept_supervisor` varchar(255) NOT NULL, `dept_desc` varchar(255) NOT NULL, `dept_email` varchar(255) NOT NULL, `dept_phone` varchar(100) NOT NULL, PRIMARY KEY (`dept_id`)) ENGINE=InnoDB AUTO_INCREMENT=23 DEFAULT CHARSET=latin1SNIPPET:/** MultiSelect v0.9.12* Copyright (c) 2012 Louis Cuny** This program is free software. It comes without any warranty, to* the extent permitted by applicable law. You can redistribute it* and/or modify it under the terms of the Do What The Fuck You Want* To Public License, Version 2, as published by Sam Hocevar. See* http://sam.zoy.org/wtfpl/COPYING for more details.*/!function ($) { "use strict"; /* MULTISELECT CLASS DEFINITION * ====================== */ var MultiSelect = function (element, options) { this.options = options; this.$element = $(element); this.$container = $('<div/>', { 'class': "ms-container" }); this.$selectableContainer = $('<div/>', { 'class': 'ms-selectable' }); this.$selectionContainer = $('<div/>', { 'class': 'ms-selection' }); this.$selectableUl = $('<ul/>', { 'class': "ms-list", 'tabindex' : '-1' }); this.$selectionUl = $('<ul/>', { 'class': "ms-list", 'tabindex' : '-1' }); this.scrollTo = 0; this.elemsSelector = 'li:visible:not(.ms-optgroup-label,.ms-optgroup-container,.'+options.disabledClass+')'; }; MultiSelect.prototype = { constructor: MultiSelect, init: function(){ var that = this, ms = this.$element; if (ms.next('.ms-container').length === 0){ ms.css({ position: 'absolute', left: '-9999px' }); ms.attr('id', ms.attr('id') ? ms.attr('id') : Math.ceil(Math.random()*1000)+'multiselect'); this.$container.attr('id', 'ms-'+ms.attr('id')); this.$container.addClass(that.options.cssClass); ms.find('option').each(function(){ that.generateLisFromOption(this); }); this.$selectionUl.find('.ms-optgroup-label').hide(); if (that.options.selectableHeader){ that.$selectableContainer.append(that.options.selectableHeader); } that.$selectableContainer.append(that.$selectableUl); if (that.options.selectableFooter){ that.$selectableContainer.append(that.options.selectableFooter); } if (that.options.selectionHeader){ that.$selectionContainer.append(that.options.selectionHeader); } that.$selectionContainer.append(that.$selectionUl); if (that.options.selectionFooter){ that.$selectionContainer.append(that.options.selectionFooter); } that.$container.append(that.$selectableContainer); that.$container.append(that.$selectionContainer); ms.after(that.$container); that.activeMouse(that.$selectableUl); that.activeKeyboard(that.$selectableUl); var action = that.options.dblClick ? 'dblclick' : 'click'; that.$selectableUl.on(action, '.ms-elem-selectable', function(){ that.select($(this).data('ms-value')); }); that.$selectionUl.on(action, '.ms-elem-selection', function(){ that.deselect($(this).data('ms-value')); }); that.activeMouse(that.$selectionUl); that.activeKeyboard(that.$selectionUl); ms.on('focus', function(){ that.$selectableUl.focus(); }); } var selectedValues = ms.find('option:selected').map(function(){ return $(this).val(); }).get(); that.select(selectedValues, 'init'); if (typeof that.options.afterInit === 'function') { that.options.afterInit.call(this, this.$container); } }, 'generateLisFromOption' : function(option, index, $container){ var that = this, ms = that.$element, attributes = "", $option = $(option); for (var cpt = 0; cpt < option.attributes.length; cpt++){ var attr = option.attributes[cpt]; if(attr.name !== 'value' && attr.name !== 'disabled'){ attributes += attr.name+'="'+attr.value+'" '; } } var selectableLi = $('<li '+attributes+'><span>'+that.escapeHTML($option.text())+'</span></li>'), selectedLi = selectableLi.clone(), value = $option.val(), elementId = that.sanitize(value); selectableLi .data('ms-value', value) .addClass('ms-elem-selectable') .attr('id', elementId+'-selectable'); selectedLi .data('ms-value', value) .addClass('ms-elem-selection') .attr('id', elementId+'-selection') .hide(); if ($option.prop('disabled') || ms.prop('disabled')){ selectedLi.addClass(that.options.disabledClass); selectableLi.addClass(that.options.disabledClass); } var $optgroup = $option.parent('optgroup'); if ($optgroup.length > 0){ var optgroupLabel = $optgroup.attr('label'), optgroupId = that.sanitize(optgroupLabel), $selectableOptgroup = that.$selectableUl.find('#optgroup-selectable-'+optgroupId), $selectionOptgroup = that.$selectionUl.find('#optgroup-selection-'+optgroupId); if ($selectableOptgroup.length === 0){ var optgroupContainerTpl = '<li class="ms-optgroup-container"></li>', optgroupTpl = '<ul class="ms-optgroup"><li class="ms-optgroup-label"><span>'+optgroupLabel+'</span></li></ul>'; $selectableOptgroup = $(optgroupContainerTpl); $selectionOptgroup = $(optgroupContainerTpl); $selectableOptgroup.attr('id', 'optgroup-selectable-'+optgroupId); $selectionOptgroup.attr('id', 'optgroup-selection-'+optgroupId); $selectableOptgroup.append($(optgroupTpl)); $selectionOptgroup.append($(optgroupTpl)); if (that.options.selectableOptgroup){ $selectableOptgroup.find('.ms-optgroup-label').on('click', function(){ var values = $optgroup.children(':not(:selected, :disabled)').map(function(){ return $(this).val();}).get(); that.select(values); }); $selectionOptgroup.find('.ms-optgroup-label').on('click', function(){ var values = $optgroup.children(':selected:not(:disabled)').map(function(){ return $(this).val();}).get(); that.deselect(values); }); } that.$selectableUl.append($selectableOptgroup); that.$selectionUl.append($selectionOptgroup); } index = index === undefined ? $selectableOptgroup.find('ul').children().length : index + 1; selectableLi.insertAt(index, $selectableOptgroup.children()); selectedLi.insertAt(index, $selectionOptgroup.children()); } else { index = index === undefined ? that.$selectableUl.children().length : index; selectableLi.insertAt(index, that.$selectableUl); selectedLi.insertAt(index, that.$selectionUl); } }, 'addOption' : function(options){ var that = this; if (options.value !== undefined && options.value !== null){ options = [options]; } $.each(options, function(index, option){ if (option.value !== undefined && option.value !== null && that.$element.find("option[value='"+option.value+"']").length === 0){ var $option = $('<option value="'+option.value+'">'+option.text+'</option>'), index = parseInt((typeof option.index === 'undefined' ? that.$element.children().length : option.index)), $container = option.nested === undefined ? that.$element : $("optgroup[label='"+option.nested+"']"); $option.insertAt(index, $container); that.generateLisFromOption($option.get(0), index, option.nested); } }); }, 'escapeHTML' : function(text){ return $("<div>").text(text).html(); }, 'activeKeyboard' : function($list){ var that = this; $list.on('focus', function(){ $(this).addClass('ms-focus'); }) .on('blur', function(){ $(this).removeClass('ms-focus'); }) .on('keydown', function(e){ switch (e.which) { case 40: case 38: e.preventDefault(); e.stopPropagation(); that.moveHighlight($(this), (e.which === 38) ? -1 : 1); return; case 37: case 39: e.preventDefault(); e.stopPropagation(); that.switchList($list); return; case 9: if(that.$element.is('[tabindex]')){ e.preventDefault(); var tabindex = parseInt(that.$element.attr('tabindex'), 10); tabindex = (e.shiftKey) ? tabindex-1 : tabindex+1; $('[tabindex="'+(tabindex)+'"]').focus(); return; }else{ if(e.shiftKey){ that.$element.trigger('focus'); } } } if($.inArray(e.which, that.options.keySelect) > -1){ e.preventDefault(); e.stopPropagation(); that.selectHighlighted($list); return; } }); }, 'moveHighlight': function($list, direction){ var $elems = $list.find(this.elemsSelector), $currElem = $elems.filter('.ms-hover'), $nextElem = null, elemHeight = $elems.first().outerHeight(), containerHeight = $list.height(), containerSelector = '#'+this.$container.prop('id'); $elems.removeClass('ms-hover'); if (direction === 1){ // DOWN $nextElem = $currElem.nextAll(this.elemsSelector).first(); if ($nextElem.length === 0){ var $optgroupUl = $currElem.parent(); if ($optgroupUl.hasClass('ms-optgroup')){ var $optgroupLi = $optgroupUl.parent(), $nextOptgroupLi = $optgroupLi.next(':visible'); if ($nextOptgroupLi.length > 0){ $nextElem = $nextOptgroupLi.find(this.elemsSelector).first(); } else { $nextElem = $elems.first(); } } else { $nextElem = $elems.first(); } } } else if (direction === -1){ // UP $nextElem = $currElem.prevAll(this.elemsSelector).first(); if ($nextElem.length === 0){ var $optgroupUl = $currElem.parent(); if ($optgroupUl.hasClass('ms-optgroup')){ var $optgroupLi = $optgroupUl.parent(), $prevOptgroupLi = $optgroupLi.prev(':visible'); if ($prevOptgroupLi.length > 0){ $nextElem = $prevOptgroupLi.find(this.elemsSelector).last(); } else { $nextElem = $elems.last(); } } else { $nextElem = $elems.last(); } } } if ($nextElem.length > 0){ $nextElem.addClass('ms-hover'); var scrollTo = $list.scrollTop() + $nextElem.position().top - containerHeight / 2 + elemHeight / 2; $list.scrollTop(scrollTo); } }, 'selectHighlighted' : function($list){ var $elems = $list.find(this.elemsSelector), $highlightedElem = $elems.filter('.ms-hover').first(); if ($highlightedElem.length > 0){ if ($list.parent().hasClass('ms-selectable')){ this.select($highlightedElem.data('ms-value')); } else { this.deselect($highlightedElem.data('ms-value')); } $elems.removeClass('ms-hover'); } }, 'switchList' : function($list){ $list.blur(); this.$container.find(this.elemsSelector).removeClass('ms-hover'); if ($list.parent().hasClass('ms-selectable')){ this.$selectionUl.focus(); } else { this.$selectableUl.focus(); } }, 'activeMouse' : function($list){ var that = this; this.$container.on('mouseenter', that.elemsSelector, function(){ $(this).parents('.ms-container').find(that.elemsSelector).removeClass('ms-hover'); $(this).addClass('ms-hover'); }); this.$container.on('mouseleave', that.elemsSelector, function () { $(this).parents('.ms-container').find(that.elemsSelector).removeClass('ms-hover'); }); }, 'refresh' : function() { this.destroy(); this.$element.multiSelect(this.options); }, 'destroy' : function(){ $("#ms-"+this.$element.attr("id")).remove(); this.$element.off('focus'); this.$element.css('position', '').css('left', ''); this.$element.removeData('multiselect'); }, 'select' : function(value, method){ if (typeof value === 'string'){ value = [value]; } var that = this, ms = this.$element, msIds = $.map(value, function(val){ return(that.sanitize(val)); }), selectables = this.$selectableUl.find('#' + msIds.join('-selectable, #')+'-selectable').filter(':not(.'+that.options.disabledClass+')'), selections = this.$selectionUl.find('#' + msIds.join('-selection, #') + '-selection').filter(':not(.'+that.options.disabledClass+')'), options = ms.find('option:not(:disabled)').filter(function(){ return($.inArray(this.value, value) > -1); }); if (method === 'init'){ selectables = this.$selectableUl.find('#' + msIds.join('-selectable, #')+'-selectable'), selections = this.$selectionUl.find('#' + msIds.join('-selection, #') + '-selection'); } if (selectables.length > 0){ selectables.addClass('ms-selected').hide(); selections.addClass('ms-selected').show(); options.prop('selected', true); that.$container.find(that.elemsSelector).removeClass('ms-hover'); var selectableOptgroups = that.$selectableUl.children('.ms-optgroup-container'); if (selectableOptgroups.length > 0){ selectableOptgroups.each(function(){ var selectablesLi = $(this).find('.ms-elem-selectable'); if (selectablesLi.length === selectablesLi.filter('.ms-selected').length){ $(this).find('.ms-optgroup-label').hide(); } }); var selectionOptgroups = that.$selectionUl.children('.ms-optgroup-container'); selectionOptgroups.each(function(){ var selectionsLi = $(this).find('.ms-elem-selection'); if (selectionsLi.filter('.ms-selected').length > 0){ $(this).find('.ms-optgroup-label').show(); } }); } else { if (that.options.keepOrder && method !== 'init'){ var selectionLiLast = that.$selectionUl.find('.ms-selected'); if((selectionLiLast.length > 1) && (selectionLiLast.last().get(0) != selections.get(0))) { selections.insertAfter(selectionLiLast.last()); } } } if (method !== 'init'){ ms.trigger('change'); if (typeof that.options.afterSelect === 'function') { that.options.afterSelect.call(this, value); } } } }, 'deselect' : function(value){ if (typeof value === 'string'){ value = [value]; } var that = this, ms = this.$element, msIds = $.map(value, function(val){ return(that.sanitize(val)); }), selectables = this.$selectableUl.find('#' + msIds.join('-selectable, #')+'-selectable'), selections = this.$selectionUl.find('#' + msIds.join('-selection, #')+'-selection').filter('.ms-selected').filter(':not(.'+that.options.disabledClass+')'), options = ms.find('option').filter(function(){ return($.inArray(this.value, value) > -1); }); if (selections.length > 0){ selectables.removeClass('ms-selected').show(); selections.removeClass('ms-selected').hide(); options.prop('selected', false); that.$container.find(that.elemsSelector).removeClass('ms-hover'); var selectableOptgroups = that.$selectableUl.children('.ms-optgroup-container'); if (selectableOptgroups.length > 0){ selectableOptgroups.each(function(){ var selectablesLi = $(this).find('.ms-elem-selectable'); if (selectablesLi.filter(':not(.ms-selected)').length > 0){ $(this).find('.ms-optgroup-label').show(); } }); var selectionOptgroups = that.$selectionUl.children('.ms-optgroup-container'); selectionOptgroups.each(function(){ var selectionsLi = $(this).find('.ms-elem-selection'); if (selectionsLi.filter('.ms-selected').length === 0){ $(this).find('.ms-optgroup-label').hide(); } }); } ms.trigger('change'); if (typeof that.options.afterDeselect === 'function') { that.options.afterDeselect.call(this, value); } } }, 'select_all' : function(){ var ms = this.$element, values = ms.val(); ms.find('option:not(":disabled")').prop('selected', true); this.$selectableUl.find('.ms-elem-selectable').filter(':not(.'+this.options.disabledClass+')').addClass('ms-selected').hide(); this.$selectionUl.find('.ms-optgroup-label').show(); this.$selectableUl.find('.ms-optgroup-label').hide(); this.$selectionUl.find('.ms-elem-selection').filter(':not(.'+this.options.disabledClass+')').addClass('ms-selected').show(); this.$selectionUl.focus(); ms.trigger('change'); if (typeof this.options.afterSelect === 'function') { var selectedValues = $.grep(ms.val(), function(item){ return $.inArray(item, values) < 0; }); this.options.afterSelect.call(this, selectedValues); } }, 'deselect_all' : function(){ var ms = this.$element, values = ms.val(); ms.find('option').prop('selected', false); this.$selectableUl.find('.ms-elem-selectable').removeClass('ms-selected').show(); this.$selectionUl.find('.ms-optgroup-label').hide(); this.$selectableUl.find('.ms-optgroup-label').show(); this.$selectionUl.find('.ms-elem-selection').removeClass('ms-selected').hide(); this.$selectableUl.focus(); ms.trigger('change'); if (typeof this.options.afterDeselect === 'function') { this.options.afterDeselect.call(this, values); } }, sanitize: function(value){ var hash = 0, i, character; if (value.length == 0) return hash; var ls = 0; for (i = 0, ls = value.length; i < ls; i++) { character = value.charCodeAt(i); hash = ((hash<<5)-hash)+character; hash |= 0; // Convert to 32bit integer } return hash; } }; /* MULTISELECT PLUGIN DEFINITION * ======================= */ $.fn.multiSelect = function () { var option = arguments[0], args = arguments; return this.each(function () { var $this = $(this), data = $this.data('multiselect'), options = $.extend({}, $.fn.multiSelect.defaults, $this.data(), typeof option === 'object' && option); if (!data){ $this.data('multiselect', (data = new MultiSelect(this, options))); } if (typeof option === 'string'){ data[option](args[1]); } else { data.init(); } }); }; $.fn.multiSelect.defaults = { keySelect: [32], selectableOptgroup: false, disabledClass : 'disabled', dblClick : false, keepOrder: false, cssClass: '' }; $.fn.multiSelect.Constructor = MultiSelect; $.fn.insertAt = function(index, $parent) { return this.each(function() { if (index === 0) { $parent.prepend(this); } else { $parent.children().eq(index - 1).after(this); } });};}(window.jQuery);//Multi-select $('#optgroup').multiSelect({ selectableOptgroup: true });.ms-container{ background: transparent url('../img/switch.png') no-repeat 50% 50%; width: 370px;}.ms-container:after{ content: "."; display: block; height: 0; line-height: 0; font-size: 0; clear: both; min-height: 0; visibility: hidden;}.ms-container .ms-selectable, .ms-container .ms-selection{ background: #fff; color: #555555; float: left; width: 45%;}.ms-container .ms-selection{ float: right;}.ms-container .ms-list{ -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075); -moz-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075); box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075); -webkit-transition: border linear 0.2s, box-shadow linear 0.2s; -moz-transition: border linear 0.2s, box-shadow linear 0.2s; -ms-transition: border linear 0.2s, box-shadow linear 0.2s; -o-transition: border linear 0.2s, box-shadow linear 0.2s; transition: border linear 0.2s, box-shadow linear 0.2s; border: 1px solid #ccc; -webkit-border-radius: 3px; -moz-border-radius: 3px; border-radius: 3px; position: relative; height: 200px; padding: 0; overflow-y: auto;}.ms-container .ms-list.ms-focus{ border-color: rgba(82, 168, 236, 0.8); -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 8px rgba(82, 168, 236, 0.6); -moz-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 8px rgba(82, 168, 236, 0.6); box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 8px rgba(82, 168, 236, 0.6); outline: 0; outline: thin dotted \9;}.ms-container ul{ margin: 0; list-style-type: none; padding: 0;}.ms-container .ms-optgroup-container{ width: 100%;}.ms-container .ms-optgroup-label{ margin: 0; padding: 5px 0px 0px 5px; cursor: pointer; color: #999;}.ms-container .ms-selectable li.ms-elem-selectable,.ms-container .ms-selection li.ms-elem-selection{ border-bottom: 1px #eee solid; padding: 2px 10px; color: #555; font-size: 14px;}.ms-container .ms-selectable li.ms-hover,.ms-container .ms-selection li.ms-hover{ cursor: pointer; color: #fff; text-decoration: none; background-color: #08c;}.ms-container .ms-selectable li.disabled,.ms-container .ms-selection li.disabled{ background-color: #eee; color: #aaa; cursor: text;}<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><select id="optgroup" class="ms" multiple="multiple"> <optgroup label="Department 1"> <option value="employee_1">Employee 1</option> <option value="employee_2">Employee 2</option> <option value="employee_3">Employee 3</option> </optgroup> <optgroup label="Department 2"> <option value="employee_4">Employee 4</option> <option value="employee_5">Employee 5</option> <option value="employee_6">Employee 6</option> </optgroup> </select> 解决方案 you should first get department names and then for each department, execute a query : <?phpecho '<select name="test[]" id="optgroup" class="ms" multiple="multiple">';$departments = mysql_query( 'SELECT DISTINCT dept_name FROM `departments`' );while( $row = mysql_fetch_array( $departments ) ){ // use some sort of character escapeing to prevent XSS echo '<optgroup label="', htmlspecialchars( $row['dept_name'] ), '">'; $users = mysql_query( sprintf( 'SELECT user_name FROM `users` WHERE users.dept = "%s"', mysql_real_escape_string( $row['dept_name'] ) ) ); while( $user = mysql_fetch_array( $users ) ){ echo '<option value="', htmlspecialchars( $user['user_name'] ), '">', htmlspecialchars( $user['user_name'] ), '</option>'; } echo '</optgroup>';}echo '</select>'; 这篇关于在 optgroups 中正确显示数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云!
08-22 17:40