javascript - 数据列表字序

标签 javascript html html-datalist

假设您有一个简单的输入字段,其中附加了一个数据列表。

<input list="suggestions>
<datalist id="suggestions">
   <option value="Apple Pie"></option>
   <option value="Strawberry Cake"></option>
</datalist>

当输入“Apple Pie”时,提示会按预期显示。但是当我将输入字段中的文本更改为“Pie Apple”时,什么也没有显示。

有没有办法让它在我以不同的顺序输入单词时显示 Apple Pie 选项?

最佳答案

这是一个纯 JavaScript 解决方案,它使用 select 元素模拟 datalist 功能。

var inp= document.querySelector('input'),
    sel= document.querySelector('select');

inp.addEventListener('input', change);
inp.addEventListener('focus', change);
inp.addEventListener('blur', function() {this.value= sel.value;});
sel.addEventListener('change', function() {inp.value= this.value;});

inp.addEventListener('keydown', function(e) {
  if(e.which === 40) {  //down arrow
    sel.selectedIndex = Math.min(sel.selectedIndex+1, sel.options.length-1);
    this.value= sel.value;
  }
  else if(e.which === 38) { //up arrow
    sel.selectedIndex = Math.max(sel.selectedIndex-1, 0);
    this.value= sel.value;
  }
});

function change() {
  var options= ['Apple Pie', 'Apple Streudel', 'Blackberry Cobbler', 'Strawberry Cake', 'Banana Pudding'],
      words= inp.value.toLowerCase().trim().split(' '),
      match,
      s= '';

  options.forEach(function(o) {
    match= true;
    words.forEach(function(w) {
      if(w > '' && 
         o.toLowerCase().indexOf(w) !== 0 && 
         o.toLowerCase().indexOf(' '+w) === -1) {
        match= false;
      }
    });
    if(match) {
      s+= '<option>'+o;
    }
  });
  sel.innerHTML= s;
  sel.size= sel.options.length;
}

inp.focus();
input, select {
  display: block;
  width: 200px;
  border: 1px solid silver;
  box-sizing: border-box;
  font: 13px arial;\
}

input:focus + select, select:focus {
  display: block;
}

select {
  display: none;
}
<input type="text">
<select></select>

关于javascript - 数据列表字序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31221322/

相关文章:

javascript - 让用户在 Node js 中注册 Handlebars 助手的安全方法

JavaScript 字符编码 + Internet Explorer 9 编码

javascript - 生态树.js : I want to get the latest version

html - 容器上的图像大小

html - 如何更改基于 :checked, 的复选框的外观,没有其他元素

javascript - HTML5 DataList 搜索可用语言?

javascript - iOS网络应用程序 "failed to parse response"

java - 在jsp中连接url

javascript - innerHTML 不适用于 IE 中的 <datalist> HTML5 元素