首页 > 解决方案 > html数据列表的自定义过滤器

问题描述

我有以下表格:

<html>

<body>
  <input type="text" list="test">
  <datalist id="test">
            <option>apple orange grape</option>
            <option>apple blueberry grape</option>
            <option>blueberry strawberry raspberry</option>
        </datalist>
</body>

</html>

正常行为是下拉框中的选项列表仅列出包含用户键入的字符串的选项。因此,如果用户键入“apple”,则会显示前两个选项。

我想使用自定义过滤器,因此如果用户键入多个单词,它会分别搜索每个单词 - 例如,如果他们键入“apple grape”,则应显示前两个选项。目前不会列出任何选项,因为没有一个选项包含字符串“apple grape”。

这可能吗?我找到了https://selectize.github.io/selectize.js/,我认为它会做我想做的事,我认为 Bootstrap 的自动完成库也可以,但我希望我可以用纯 HTML/JS 做到这一点。

e:我认为这是描述我正在尝试做的事情的另一种方式:

var a = ["apple orange grape", "apple blueberry grape", "blueberry strawberry raspberry"];

function filter(t) {
  var filterTerms = t.value.split(" ");
  var select = document.getElementById("select");
  select.innerHTML = "";
  for (var i = 0; i < a.length; i++) {
    var match = true;
    for (var j = 0; j < filterTerms.length; j++) {
      if (a[i].indexOf(filterTerms[j]) == -1) {
        match = false;
      }
    }
    if (match) {
      select.appendChild(new Option(a[i], a[i]));
    }
  }
}
<input type="text" id="filtertest" onkeyup="filter(this);">
<select id="select">
</select>

该 JS 使它成为select数组中唯一a与文本输入中的过滤器匹配的选项。我想将文本输入和select(如文本输入与datalist)结合起来。

标签: javascripthtml

解决方案


你想做的事情没有多大意义。如果用户键入“apple grape”,那么脚本在键入时应该做什么?它是否应该已经开始搜索“appl”,或者它应该如何知道您已完成输入并想要查找字符串(没有“立即搜索”按钮)。

基于 jquery,您可以在键入时缩小列表

$("document").ready(function () {

    $("#InputBox").on("keyup", function () {
        var searchText = $(this).val();
        searchText = searchText.toLowerCase();
        searchText = searchText.replace(/\s+/g, '');
        $('#myList > li').each(function(){
            var currentLiText = $(this).text(),
                showCurrentLi = ((currentLiText.toLowerCase()).replace(/\s+/g, '')).indexOf(searchText) !== -1;

            $(this).toggle(showCurrentLi);

        });
    });
    inactivityTime();
});

推荐阅读