如何在 select2 中获取搜索查询?

How do I get a search query in select2?

我想获取搜索查询。但是我不知道如何获取搜索查询。

这不起作用:

var term = $selectField.data("select2").dropdown.$search.val();

在我的代码中,我试图在 formatResult 部分中获取搜索查询。但是变量项是未定义的。你能告诉我我做错了什么吗?

$selectField.select2({
        width: '500px',
        formatResult: function(data) {

            var term = $selectField.data("select2").dropdown.$search.val();

            var text = data.text;
            if (text.includes("/")){
                var repository = getBranchAndRepositoryFromDevLine(text)[0];
                var branch = getBranchAndRepositoryFromDevLine(text)[1];
                var $result = $('<span/>',{
                    class: "branch",
                    text: branch
                }).add($('<span/>',{
                    class: "repository",
                    text: repository}));
                return $result;
            } else{
                var $result = $("<span></span>");
                $result.text(text);
                return $result;
            }
        },
        formatSelection: function(data) {
            var text = data.text;
            if (text.includes("/")){
                var branch = getBranchAndRepositoryFromDevLine(text)[1];
                return branch;
            }
            return text;
        },
        ajax: {
            url: "/rest/solution-delivery/1.0/branch/branch-picker/project-branches",
            cache: false,
            dataType: 'json',
            data: function (params) {
                return {
                    projectId: projectId,
                    query: params,
                    isCommitAllowed: true
                };
            },
            results: function (data, params) {
                return {
                    results: data.sections
                };
            },
            formatNoMatches: function formatNoMatches(query) {
                return "No matches found";
            }
        }
    })

如问题评论中所述,您当前使用的是 Select2 的旧版本,推测为 Select v3.5.2 或相似的。 v4 之前的版本有不同的选项,即必须传递 formatResult 来格式化问题中使用的结果。关于这方面的文档可以在页面的中间位置 here 找到。

文档显示传递给 formatResult 函数的参数是:

formatResult(object, container, query)

其中第三个参数query定义为The query object used to request this set of results.。此 query 对象包含作为 term 属性 的搜索。因此,下面打印输入的搜索查询。

formatResult: function(object, container, query) {
  var term = query.term;
  console.log('search term is', term);
}

这已包含在 https://jsfiddle.net/j89q15d6/ 的示例中,也包含在下面的页面中。出于演示目的,该示例将搜索词附加到结果文本的方括号中。

// Template function which adds CSS flag and displays country name
function flagTemplate(object, container, query) {
  let term = "";
    
  // Check the search term, if one is found set term variable to be included in result
  if (query.term) {
    //  search term is set
    term = " (" + query.term + ")";
  }
  
  // Append the search term to the result, just for testing
  return $("<span class='flag-icon flag-icon-" + object.id + " '></span><span class='flag-text'>" + object.text + term + "</span>");
}

// Generate the correct URL
function generateUrl(term) {
  if (term) {
    return "https://restcountries.com/v3.1/name/" + term;
  } else {
    return "https://restcountries.com/v3.1/all";
  }
}

// Initialise select2
var $selectField = $('#countrySelect');
$selectField.select2({
  width: "element",
  // Set template for results and selection
  formatResult: flagTemplate,
  formatSelection: flagTemplate,
  // Set placeholder text
  placeholder: 'Select country...',
  // Load country list from https://restcountries.com
  ajax: {
    url: generateUrl,
    delay: 250,
    dataType: "json",
    results: function(data) {
      return {
        results: data
          .map(x => ({
            id: x.cca2.toLowerCase(),
            text: x.name.official
          }))
          .sort((a, b) => ('' + a.text).localeCompare(b.text))
      };
    }
  }
});
#countrySelect {
  width: 300px;
}

.flag-text {
  margin-left: 10px;
}
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/select2/3.5.2/select2.css" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/3.5.2/select2.js"></script>

<!-- Load flags using library https://github.com/lipis/flag-icons  -->
<link href="https://cdnjs.cloudflare.com/ajax/libs/flag-icon-css/4.1.5/css/flag-icons.min.css" rel="stylesheet"/>

<div>Select v3.5.2 Example</div>
<input type="hidden" id="countrySelect">