Select2 - 按查询排序结果 [英] Select2 - Sorting results by query

查看:263
本文介绍了Select2 - 按查询排序结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Select2版本4.0.0。

I'm using Select2 version 4.0.0.

如果我的结果包含多个单词,并且用户输入其中一个单词,我需要b $ b b显示按输入的单词在结果中的位置排序的结果。

If my results contain multiple words, and the user enters one of those words, I want to display the results sorted by where the entered word is within the result.

例如,用户输入apple,我的结果是:

For example, a user enters "apple", and my results are:


  1. 香蕉橙苹果

  2. 香蕉苹果橙

  3. 苹果香蕉橙

然后apple banana orange应首先出现在select2结果列表中,因为这是结果苹果最早出现在结果中。我对过去的订购并不在意。

Then "apple banana orange" should appear first in the list of select2 results, because that is the result in which "apple" appears earliest within the result. I don't care so much about the ordering past that.

我应该覆盖或配置什么来获得这样的东西?似乎 matcher 没有
处理订单, sorter 不包含查询数据。

What do I override or configure to get something like this? It seems that matcher doesn't handle ordering, and sorter doesn't contain query data.

推荐答案

您可以通过使用 select2-search__field class。这可能会打破各个版本,但由于他们没有提供钩子来获取查询,因此需要某种黑客攻击。您可以提交问题,让他们在排序期间添加对访问查询的支持,尤其是看起来它在Select2 3.5.2中是可能的。

You could grab the search query from the value of the input box generated by Select2 by identifying it with the select2-search__field class. That's probably going to break across versions, but since they don't provide a hook to get the query some sort of hack will be needed. You could submit an issue to have them add support for accessing the query during sort, especially since it looks like it was possible in Select2 3.5.2.

$('#fruit').select2({
  width: '200px',
  sorter: function(results) {
    var query = $('.select2-search__field').val().toLowerCase();
    return results.sort(function(a, b) {
      return a.text.toLowerCase().indexOf(query) -
        b.text.toLowerCase().indexOf(query);
    });
  }
});

<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/select2/4.0.0/js/select2.min.js"></script>
<link href="//cdnjs.cloudflare.com/ajax/libs/select2/4.0.0/css/select2.min.css" rel="stylesheet" />

<select id="fruit">
  <option>Banana Orange Apple</option>
  <option>Banana Apple Orange</option>
  <option>Apple Banana Orange</option>
  <option>Achocha Apple Apricot</option>
  <option>Durian Mango Papaya</option>
  <option>Papaya</option>
  <option>Tomato Papaya</option>
  <option>Durian Tomato Papaya</option>
</select>

这篇关于Select2 - 按查询排序结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆