繁体   English   中英

如何在select2下拉列表中隐藏选项上的一些文本?

[英]How to hide some text on options in select2 dropdown?

我在 select2 下拉列表中有一个这样的产品列表。

<option>Product A [Barcode]</option>
<option>Product A [Barcode]</option>
<option>Product A [Barcode]</option>
<option>Product A [Barcode]</option>

现在我想从选项中隐藏条形码,但希望在输入条形码时搜索找到产品。 我试过

<option>Product A <span style='display:none;'>[Barcode]</span></option>

但没有成功。 无法在文档中找到答案。 请帮忙。

选项元素内部不能有任何子元素,因此您可以在选项的“值”属性中移动条形码值。然后定义 select2 匹配器函数来搜索选项值。

https://select2.org/searching

$('#mySelect').select2({
  matcher: function(params, data) {
    // If there are no search terms, return all of the data
    if ($.trim(params.term) === '') { return data; }
    // Do not display the item if there is no 'text' property
    if (typeof data.text === 'undefined') { return null; }

    // check for both value and text
    var searchTarget = params.term.toLowerCase();
    if (data.text.toLowerCase().indexOf(searchTarget) > -1 || data.id.toLowerCase().indexOf(searchTarget) > -1) {
        return $.extend({}, data, true);
    }
    //
    return null;
}
});

结果是这样的:

https://jsfiddle.net/scarabs/canrx12k/

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM