2016-01-24 59 views
0

我在html中搜索类似datalist的东西。当我在html输入中输入内容时,它会在数据库中显示类似的标题。当我输入更多内容时,ajax会向我显示更好的匹配标题。我有这个ajax脚本,但我的问题在这里:我怎样才能在输入文本下呈现这个标题?类似数据列表

我在google上看到它只有ul和li标签,而且都是? google search example

但在w3schools example我们可以看到更好的解决方案。

哪一个更好?或者如果你知道其他技术,请告诉我。不知道在我的搜索工具中使用哪一个。

+0

你的链接是非常有帮助的,但我并不热衷于添加插件到这个困境。我发现这[这个](http://codepen.io/matt-west/pen/jKnzG) – kjugi

回答

0

我想我找到解决方案的评论与有用的链接,不记得是谁,因为他删除了他的评论。

通过这个环节,我开始seraching DataList和发现的文章: blog link

在这里,我们对数据列表一些短语和非常有用的例子:

<div id="page-wrapper"> 
    <h1>Datalist Element Demo</h1> 

    <label for="default">Pick a programming language</label> 
    <input type="text" id="default" list="languages" placeholder="e.g. JavaScript"> 

    <datalist id="languages"> 
    <option value="HTML"> 
    <option value="CSS"> 
    <option value="JavaScript"> 
    <option value="Java"> 
    <option value="Ruby"> 
    <option value="PHP"> 
    <option value="Go"> 
    <option value="Erlang"> 
    <option value="Python"> 
    <option value="C"> 
    <option value="C#"> 
    <option value="C++"> 
    </datalist> 


    <label for="ajax">Pick an HTML Element (options loaded using AJAX)</label> 
    <input type="text" id="ajax" list="json-datalist" placeholder="e.g. datalist"> 
    <datalist id="json-datalist"></datalist> 


</div> 

<script> 
    // Get the <datalist> and <input> elements. 
    var dataList = document.getElementById('json-datalist'); 
    var input = document.getElementById('ajax'); 

    // Create a new XMLHttpRequest. 
    var request = new XMLHttpRequest(); 

    // Handle state changes for the request. 
    request.onreadystatechange = function(response) { 
     if (request.readyState === 4) { 
     if (request.status === 200) { 
      // Parse the JSON 
      var jsonOptions = JSON.parse(request.responseText); 

      // Loop over the JSON array. 
      jsonOptions.forEach(function(item) { 
      // Create a new <option> element. 
      var option = document.createElement('option'); 
      // Set the value using the item in the JSON array. 
      option.value = item; 
      // Add the <option> element to the <datalist>. 
      dataList.appendChild(option); 
      }); 

      // Update the placeholder text. 
      input.placeholder = "e.g. datalist"; 
     } else { 
      // An error occured :(
      input.placeholder = "Couldn't load datalist options :("; 
     } 
     } 
    }; 

    // Update the placeholder text. 
    input.placeholder = "Loading options..."; 

    // Set up and make the request. 
    request.open('GET', 'https://s3-us-west-2.amazonaws.com/s.cdpn.io/4621/html-elements.json', true); 
    request.send(); 
</script> 

我得到这个在文章codepen链接。由Matt West创建的笔。