使用Typeahead.js突出显示多个单词

时间:2015-08-20 10:35:47

标签: javascript search autocomplete typeahead.js

我使用typeahead.js进行自动填充,就像在this official example中一样。

当我搜索" rh"这导致" Rh ode Island" (匹配的字符是高亮的)。

当我搜索" rh是"这导致"罗德岛" (没有任何突出显示)。我怎样才能让它发挥作用?预期结果:" Rh ode 土地"。

P.S。如果这需要修改source code,那么这对我来说没问题。

2 个答案:

答案 0 :(得分:4)

typeahead的默认集成突出显示组件不够智能,无法满足您的要求。

我给你一个mark.js示例,这是一个用于搜索字词/关键字或自定义正则表达式的文本突出显示器。请查看网站以了解有关API的更多信息。

DEMO JSFIDDLE

$(function() {
  // constructs the suggestion engine
  var states = ['Alabama', 'Alaska', 'Arizona', 'Arkansas', 'California',
    'Colorado', 'Connecticut', 'Delaware', 'Florida', 'Georgia', 'Hawaii',
    'Idaho', 'Illinois', 'Indiana', 'Iowa', 'Kansas', 'Kentucky', 'Louisiana',
    'Maine', 'Maryland', 'Massachusetts', 'Michigan', 'Minnesota',
    'Mississippi', 'Missouri', 'Montana', 'Nebraska', 'Nevada', 'New Hampshire',
    'New Jersey', 'New Mexico', 'New York', 'North Carolina', 'North Dakota',
    'Ohio', 'Oklahoma', 'Oregon', 'Pennsylvania', 'Rhode Island',
    'South Carolina', 'South Dakota', 'Tennessee', 'Texas', 'Utah', 'Vermont',
    'Virginia', 'Washington', 'West Virginia', 'Wisconsin', 'Wyoming', 'take bag'
  ];
  var states = new Bloodhound({
    datumTokenizer: Bloodhound.tokenizers.whitespace,
    queryTokenizer: Bloodhound.tokenizers.whitespace,
    // `states` is an array of state names defined in "The Basics"
    local: states
  });

  // Initialize typeahead with mark.js
  var $context = $("#bloodhound");
  $context.find(".typeahead").typeahead({
    hint: true,
    // disable integrated typeahead component
    highlight: false,
    minLength: 1
  }, {
    name: 'states',
    source: states
  }).on("typeahead:render", function() {
    // highlight matches with mark.js
    var searchTerm = $(this).val();
    $context.find(".tt-menu").mark(searchTerm);
  });
});
input {
  width: 250px;
  padding: 3px;
}

mark {
  background: yellow;
  color: black;
}
<script src="https://code.jquery.com/jquery-2.2.4.min.js"></script>
<script src="https://cdn.rawgit.com/julmot/mark.js/6.1.0/dist/jquery.mark.min.js"></script>
<script src="https://cdn.rawgit.com/twitter/typeahead.js/v0.11.1/dist/typeahead.bundle.min.js"></script>
<!-- Demo taken from http://twitter.github.io/typeahead.js/examples/ -->
<div id="bloodhound">
  <input class="typeahead" type="text" placeholder="States of USA. Type in 'rh is' or 'bag take'">
</div>

首先,您必须禁用默认的集成突出显示组件(默认情况下禁用)。然后,您将必须侦听渲染器事件并初始化{* 3}}有关预先输入的建议。

答案 1 :(得分:-1)

我认为如果您将\s模式添加到_.escapeRegExChars()帮助程序中使用的正则表达式(请参阅here),它将解决您的问题。

我不确定,因为我没有从笔记本电脑上回答,我也无法进行测试,但你现在可以尝试让我。

相关问题