用于搜索UL列表的搜索框或自动完成文本框

search box or autocomplete text box for search UL list

本文关键字:搜索 文本 列表 用于 UL      更新时间:2023-09-26

我需要一个搜索框或自动完成文本框来从列表中搜索指定的值使用JQUERY或JAVASCRIPT。

例如:默认情况下,列表中的所有值都显示在文本框下。

当我在文本框中输入"a"的意思时,就会显示从"a"开始的单词。

<input id="tags" />
<div id="xxx">
<ul id="autocompletes1">
<li><a href="index.html">Acura</a></li>
<li><a href="index.html">Audi</a></li>
<li><a href="index.html">BMW</a></li>
<li><a href="index.html">Cadillac</a></li>
<li><a href="index.html">Chrysler</a></li>
<li><a href="index.html">Dodge</a></li>
<li><a href="index.html">Ferrari</a></li>
</ul>
</div>

此代码将适用于您的UL列表,但您最好使用javascript插件。。。

$('#tags').on('keyup',function(e){
  // cache all the tag elements in an array
  var tagElems = $('#autocompletes1').children();
  // hide all tags
  $(tagElems).hide();

  for(var i = 0; i < tagElems.length; i++){ // loop through all tagElements
    var tag = $(tagElems).eq(i);
    if(($(tag).text().toLowerCase()).indexOf($(this).val().toLowerCase()) === 0){
      // if element's text value starts with the hint show that tag element
      $(tag).show();
    }
  }
});

Working Example没有标记选择逻辑。。。

Example with tag selection logic

使用此代码:

$(function() {
    var availableTags = [];
    $('#autocompletes1 li').each(function(){
        availableTags.push($(this).text());
    });

    $( "#tags" ).autocomplete({
      source: availableTags
    });
  });

FIDDLE演示

注意:必须使用jquery ui

var sources = [];
$('span').each(function(i,ele){
  sources.push({'label': $(ele).text(), 'value' : i});
});
$( "#tags" ).autocomplete({
    source: sources
});

无序的JSFIDDLE