如何运行这个html组合框样例

How to run this html combobox sample?

本文关键字:html 组合 样例 何运行 运行      更新时间:2023-09-26

大家好,我一直在寻找一个简单的例子,如何使html选择看起来像一个组合框。我从这个链接中找到了一个示例代码片段。这实际上是对一个类似于我的问题的回答。它的答案是Samich。它有一个简洁的链接。我从jsfiddle中复制了代码,并稍微调整了一下,使它能在我的机器上运行,但我不能使它运行。

下面是代码(大部分代码是由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所以请忍受我的家伙。

<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>

差不多了!您需要确保将事件附加到元素的脚本在浏览器创建元素之后运行,只需使用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);
        });
     });

为什么不使用作为jQuery UI一部分的comboBox呢?

如果您使用<a href="#" id="btn">V</a>则使用do $('btn')而不是$('#btn')