大家好我一直在寻找一个关于如何使html选择看起来像组合框的简单示例。我找到了this link的示例代码段。它实际上是一个类似于我的问题的答案。它由Samich
回答。它有一个jsfiddle link。我从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很新,所以请耐心等待我们。非常感谢。
答案 0 :(得分: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>
答案 1 :(得分: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);
});
});
答案 2 :(得分:0)
答案 3 :(得分:-2)
如果您使用<a href="#" id="btn">V</a>
,则使用do $('btn')
而不是$('#btn')
...