layui-select-multiple
layui-select-multiple copied to clipboard
使用了optgroup 元素之后,其内部的 option 元素全显示在 span 里面了
RT,应该对 item
参数进行判断,如果它的 tagName
是 OPTION
,按照正常流程走;tagName
是 OPTGROUP
的话,可以把 <optgroup>
的 label
属性显示出来。
HTML 结构如下:
<select name="简化多选+搜索+大小写敏感" multiple lay-search lay-case lay-omit>
<option value="">请选择您的兴趣爱好</option>
<optgroup label="group1">
<option>option11</option>
<option>option12</option>
<option>option13</option>
<option>option14</option>
</optgroup>
<optgroup label="group2">
<option>option21</option>
<option>option22</option>
<option>option23</option>
<option>option24</option>
</optgroup>
</select>
如上图所示,左边是我修改后的,右边是修改前的。form.js
部分修改内容如下:
第一处
notOption(value, function(none){
if(none){
// 将 p 元素改成 dd 元素,HTML 语义更合法 :-)
dl.find('.'+NONE)[0] || dl.append('<dd class="'+ NONE +'">无匹配项</dd>');
} else {
dl.find('.'+NONE).remove();
}
}, 'keyup');
第二处
layui.each(options, function (index, item) {
if (index === 0 && !item.value) {
if (isSearchInput) {
// 优化搜索框样式
arr.push('<dd lay-value="" class="layui-select-tips" style="padding-right:10px;margin-bottom:5px;cursor:auto;display:block!important"><input class="layui-input" style="cursor:auto;padding-right:10px" placeholder="关键字搜索"></dd>');
} else {
arr.push('<dd lay-value="" class="layui-select-tips">' + (item.innerHTML || TIPS) + '</dd>');
}
}else {
if (index === 1 && isSearchInput) {
/**
* 此处优化了 HTML 语义,div 和 dd 元素不应该在 "<dl>...</dl>" 中并列显示
* 故改为 "<dd><dl><dd>...</dd><dd>...</dd></dl></dd>" 这样合法的嵌套模式 :-)
*/
arr.push('<dd style="max-height:247px;overflow-y:auto"><dl style="position:relative;border:0 none;top:0;padding-top:0;max-height:initial">')
}
if(value != null && value != undefined && value.length != 0) {
for (var checkedVal = 0; checkedVal < value.length; checkedVal++) {
if (value[checkedVal] == item.value) {
arr.push('<dd lay-value="' + item.value + '">' + '<input type="checkbox" ' + (item.disabled ? "disabled" : "") + ' checked lay-filter="searchChecked" title="' + item.innerHTML + '" lay-skin="primary"></dd>');
return false;
}
}
}
if ($(item).prop("tagName") === "OPTGROUP") {
// 如果是 OPTGROUP 元素,将其 label 属性放在 dd 元素中
arr.push('<dd style="padding-left:10px;cursor:default"><strong>' + $(item).attr("label") + '</strong></dd>');
} else {
// 如果是 OPTION 元素,保持原来的模式渲染
arr.push('<dd lay-value="' + item.value + '">' + '<input type="checkbox" ' + (item.disabled ? "disabled" : "") + ' lay-filter="searchChecked" title="' + item.innerHTML + '" lay-skin="primary"></dd>');
}
}
});
arr.length === 0 && arr.push('<dd lay-value="" class="' + DISABLED + '">没有选项</dd>');
if (isSearchInput) {
// 呼应上面的结尾,将 "</div>" 改为 "</dl></dd>"
arr.join("</dl></dd>");
}
最后,感谢作者的改出这么好用的多选下拉框,如果有 ⌈点击 optgroup
的 label
,直接全选其内部的 option
⌋ 这种操作就更好了:clap: 在下不才,只能先改这么点。另外,作者你的 demo 该更新啦!