Select2 - Sorting results by query

可紊 提交于 2020-01-10 13:11:10

问题


I'm using Select2 version 4.0.0.

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.

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

  1. "banana orange apple"
  2. "banana apple orange"
  3. "apple banana orange"

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.

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.


回答1:


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>



回答2:


The problem here is that Select2, in the 4.0.0 release, separated the querying of results from the display of results. Because of this, the sorter option which you would normally use to sort the results does not pass in the query that was made (which includes the search term).

So you are going to need to find a way to cache the query that was made so you can use it when sorting. In my answer about underlining the search term in results, I cache the query through the loading templating method, which is always triggered whenever a search is being made. That same method can be used here as well.

var query = {};

$element.select2({
  language: {
    searching: function (params) {
      // Intercept the query as it is happening
      query = params;

      // Change this to be appropriate for your application
      return 'Searching…';
    }
  }
});

So now you can build a custom sorter method which uses the saved query (and using query.term as the search term). For my example sorting method, I'm using the position within the text where the search result is to sort results. This is probably similar to what you are looking for, but this is a pretty brute force method of going about it.

function sortBySearchTerm (results) {
  // Don't alter the results being passed in, make a copy
  var sorted = results.slice(0);

  // Array.sort is an in-place sort
  sorted.sort(function (first, second) {
    query.term = query.term || "";

    var firstPosition = first.text.toUpperCase().indexOf(
      query.term.toUpperCase()
    );
    var secondPosition = second.text.toUpperCase().indexOf(
      query.term.toUpperCase()
    );

    return firstPosition - secondPosition;
  });

  return sorted;
};

And this will sort things the way that you are looking to do it. You can find a full example with all of the parts connected together below. It's using the three example options that you mentioned in your question.

var query = {};
var $element = $('select');

function sortBySearchTerm (results) {
  // Don't alter the results being passed in, make a copy
  var sorted = results.slice(0);
  
  // Array.sort is an in-place sort
  sorted.sort(function (first, second) {
    query.term = query.term || "";

    var firstPosition = first.text.toUpperCase().indexOf(
      query.term.toUpperCase()
    );
    var secondPosition = second.text.toUpperCase().indexOf(
      query.term.toUpperCase()
    );
    
    return firstPosition - secondPosition;
  });
  
  return sorted;
};

$element.select2({
  sorter: sortBySearchTerm,
  language: {
    searching: function (params) {
      // Intercept the query as it is happening
      query = params;

      // Change this to be appropriate for your application
      return 'Searching…';
    }
  }
});
<link href="//cdnjs.cloudflare.com/ajax/libs/select2/4.0.0/css/select2.css" rel="stylesheet"/>

<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/select2/4.0.0/js/select2.js"></script>

<select style="width: 50%">
  <option>banana orange apple</option>
  <option>banana apple orange</option>
  <option>apple banana orange</option>
</select>



回答3:


No needs to keep term:

$element.select2({
    sorter: function (data) {
        if(data && data.length>1 && data[0].rank){
            data.sort(function(a,b) {return (a.rank > b.rank) ? -1 : ((b.rank > a.rank) ? 1 : 0);} );
        }
        return data;
    }
    ,
    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;
        }

        // `params.term` should be the term that is used for searching
        // `data.text` is the text that is displayed for the data object
        var idx = data.text.toLowerCase().indexOf(params.term.toLowerCase());
        if (idx > -1) {
          var modifiedData = $.extend({
            // `rank` is higher when match is more similar. If equal rank = 1
              'rank':(params.term.length / data.text.length)+ (data.text.length-params.term.length-idx)/(3*data.text.length)
          }, data, true);

          // You can return modified objects from here
          // This includes matching the `children` how you want in nested data sets
          return modifiedData;
        }

        // Return `null` if the term should not be displayed
        return null;
    }

})



来源:https://stackoverflow.com/questions/31991217/select2-sorting-results-by-query

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!