2014-10-29 80 views
0
$ (function() { 
    var heroes = [ 
    "Abaddon", 
    "Alchemist", 
    "Ancient Apparition", 
    "Anti-Mage", 
    "Axe", 
    "Bane", 
]; 

document.getElementById('searchBar').onkeyup = searchDropDown; 

function searchDropDown(){ 

    var search = heroes[i]; 

    for (var i = 0; i < search.length; i++) { 

     if (search.indexOf(document.getElementById("searchBar"))> - 1) { 

      alert("Sucess") 
     } 
    } 
    } 

}); 

所以这是我的javascript代码,我无法让它工作。尝试了解如何使用下拉列表创建搜索栏,与facebook的搜索栏相同。带下拉结果的搜索栏

任何人都可以帮助我或善意地把我放在正确的道路上? :)

回答

1

你可以做一个下拉列表与HTML元素:

<input list="heroes" type="text" id="searchBar"> 
<datalist id="heroes"> 
    <option value="Abaddon"> 
    <option value="Alchemist"> 
    <option value="Ancient Apparition"> 
    <option value="Anti-Mage"> 
    <option value="Axe"> 
    <option value="Bane"> 
</datalist> 

如果你有写在JS或JSON更大的英雄榜。你可以这样做:

<input list="heroes" type="text" id="searchBar"> 
<datalist id="heroes"></datalist> 
<script> 
    var heroes = [ 
     "Abaddon", 
     "Alchemist", 
     "Ancient Apparition", 
     "Anti-Mage", 
     "Axe", 
     "Bane", 
    ]; 

    for (var key in heroes) { 
     var optionElement = document.createElement("option"); 
     optionElement.value = heroes[key]; 
     document.getElementById("heroes").appendChild(optionElement); 
    } 
</script> 
+0

对不起,我可怜的描述。但为了这个例子,我只带了几个英雄,我还有一个70多个英雄可以加入。谢谢 – DACA92 2014-10-29 08:53:43

+0

然后在datalist中为每个英雄添加一行。如果你在Javascript中有你的列表,你可以用一个简单的JavaScript代码填充数据列表。 – 2014-10-29 08:57:11

+0

@ DACA92通过JavaScript数组或JSON运行循环 – Ashish 2014-10-29 08:57:44

0

首先,您需要在您的网页jQuery的,因为是的onkeyup的jQuery的事件。

在如果比较场与搜索的价值,你需要得到输入的值与

<html> 
    <script src="jquery.min.js"></script> 
    <script> 
    $(document).ready(function() { 
     var heroes = [ 
      "Abaddon", 
      "Alchemist", 
      "Ancient Apparition", 
      "Anti-Mage", 
      "Axe", 
      "Bane", 
     ]; 

    document.getElementById('searchBar').onkeyup = searchDropDown; 

    function searchDropDown(){ 
     for (var i = 0; i < heroes.length; i++) { 
      search = heroes[i];  
      if (search.indexOf(document.getElementById("searchBar").value)> - 1) { 
       //Use console.log, not alert, to depure is the best because you print object and navigate inside them 
       //For view output, Chrome or IE -> press F12, Firefox -> install firebug and press F12. And go tab "Console" 
       console.log("the word find:" + search); 
      } 
     } 
    } 
}); 

</script> 
<body> 
    <input type="text" id="searchBar"/> 
</body> 
</html> 

对不起我的英文不好,;)