【问题标题】:Changing search behavior in jquery plugin Chosen更改 jquery 插件中的搜索行为选择
【发布时间】:2018-06-13 14:31:15
【问题描述】:

我正在为 jQuery 使用 Chosen 插件,并希望搜索行为有所改变(单选)。搜索仅会导致匹配字符串中单词开头的命中。我想将其扩展为在斜线和括号之后也命中单词。

例如: 搜索字符串:“second”与项目“first/second”或“first(second)”不匹配。

我怀疑这是否可以通过简单地向构造函数添加选项来改变,但我愿意更改/硬编码源脚本。

选择:https://github.com/harvesthq/chosen

【问题讨论】:

    标签: jquery jquery-plugins


    【解决方案1】:

    正如在最近的一些答案中提到的,该插件现在实现了一个更改搜索行为的选项:

    search_contains: true
    

    Options documentation


    插件不提供更改搜索方法行为的选项。

    如果您愿意更改插件源本身,这里有一个方法。

    在插件中进行搜索的方法是Chosen.prototype.winnow_results。它使用正则表达式匹配以搜索词“开头”的文本:

    // "^": means "starts with"
    // "searchText" is the text in the search input (it is just cleaned up don't be scared)
    regex = new RegExp('^' + searchText.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&"), 'i');
    

    改成:

    regex = new RegExp(searchText.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&"), 'i');
    

    DEMO

    【讨论】:

    • 非常好!这也会导致 searchTerm="cond" 的命中,而我实际上并没有寻找,但在这种情况下它是完全可以接受的。
    • 看看下面@DirkNguyen 的回答。它是最新的,现在不需要修改插件。
    【解决方案2】:

    可以使用search_contains选项设置搜索行为

    默认是false

    将其设置为true,并且选择也会在里面找到匹配项,而不仅仅是开头:

    $('#my_dropdown').chosen({ search_contains: true });
    

    【讨论】:

    • 今天选择的版本似乎在 word 的开头搜索:所以如果我在输入中键入 t 并且绑定到所选对象的 select 有'Some text' 之类的选项,它将列在下拉列表中...有没有办法禁止这种行为并真正只从选项文本的开头进行搜索?
    • 是否出于性能原因默认禁用此功能?如果是,性能变化有多大。
    【解决方案3】:

    与 Chosen 1.0 一样,只需添加选项 {search_contains: true}

    $('.selector').chosen({search_contains: true});
    

    玩得开心。

    【讨论】:

      【解决方案4】:

      在选择的 1.0 中,我在第 301 和 302 行做了

      escapedSearchText = searchText.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
      regexAnchor = "";
      

      【讨论】:

        【解决方案5】:

        选项中有search_contains选项可用于搜索子字符串,可以用作:

        $(".chosen-select").chosen({
            search_contains: true
        });
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2012-04-20
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2012-02-17
          • 1970-01-01
          相关资源
          最近更新 更多