2011-11-18 67 views
1

大家好我一直在尋找一個簡單的例子,如何使html選擇像組合框出現。我從this link發現了一個示例代碼片段。它其實是一個類似於我的問題的答案。它的回答是Samich。它有一個jsfiddle link。我從jsfiddle複製了代碼,並稍微調整了它以使其在我的機器上運行,但我無法使其運行。如何運行這個html combobox示例?

這裏是代碼(大部分的代碼都是由Samich寫):

<html> 
    <head> 
     <style type="text/css"> 
      #dropdown { position:absolute; width:200px; display:none; } 
      #dropdown li:hover { background:#ccc; cursor:pointer; } 
     </style> 
     <script type="text/javascript" src="jquery1.6.4min.js"></script> 
     <script type="text/javascript" > 
      $('#btn').click(function() { 
       var pos = $('#txt').offset(); 
       pos.top += $('#txt').width(); 
       $('#dropdown').fadeIn(100); 
       return false; 
      }); 

      $('#dropdown li').click(function() { 
       $('#txt').val($(this).text()); 
       $(this).parent().fadeOut(100); 
      }); 
     </script> 
    </head> 

    <body> 
     <input type="text" id="txt" /><a href="#" id="btn">V</a> 
     <ul id="dropdown"> 
      <li>Value 1</li> 
      <li>Value 2</li> 
      <li>Value 3</li> 
      <li>Value 4</li> 
      <li>Value 5</li> 
      <li>Value 6</li> 
      <li>Value 7</li> 
      <li>Value 8</li> 
      <li>Value 9</li> 
      <li>Value 10</li> 
      <li>Value 11</li> 
      <li>Value 12</li> 
     </ul> 
    </body> 
</html> 

我非常的JavaScript和jQuery新,所以請多多包涵傢伙。提前致謝。

+0

您的jQuery JavaScript文件的src是否正確?也許它應該是'jquery.1.6.4.min.js'? –

+0

@TimBJames現在工作。我只是忘了$(document).ready(function() – NinjaBoy

回答

1
<script type="text/javascript"> 
$(document).ready(function() { 
    $('#btn').click(function() { 
    var pos = $('#txt').offset(); 
    pos.top += $('#txt').width(); 

    $('#dropdown').fadeIn(100); 

    return false; 
    }); 

    $('#dropdown li').click(function() { 
    $('#txt').val($(this).text()); 
    $(this).parent().fadeOut(100); 
    }); 
}); 
</script> 
-2

如果使用<a href="#" id="btn">V</a>然後do $('btn')$('#btn') ...

+0

我改變$('#btn')。click(function()to $('btn')。click(function()but still not working。 – NinjaBoy

+2

You正在做正確的使用$('#btn') – Cyclonecode

+0

@KristerAndersson +1,因爲原因是我無法放置$(document).ready – NinjaBoy

1

差不多!您需要確保將元素附加到元素的腳本在之後運行,這些元素已由瀏覽器創建,只需使用ready()函數;

 $(document).ready(function() { 
     $('#btn').click(function() { 
      var pos = $('#txt').offset(); 
      pos.top += $('#txt').width(); 
      $('#dropdown').fadeIn(100); 
      return false; 
     }); 

     $('#dropdown li').click(function() { 
      $('#txt').val($(this).text()); 
      $(this).parent().fadeOut(100); 
     }); 
    }); 
+0

非常感謝。與克里斯特有非常相似的答案,但他首先回答,非常感謝解釋。 – NinjaBoy