2014-10-29 81 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> 

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