来自@maha-raja的原始问题:
“在Twitter Bootstrap按钮下拉列表中启用搜索的方法有哪些?
我在网页中使用bootstrap按钮下拉列表。由于列表中包含20多个项目,因此我选择滚动选项。现在我需要一种方法来启用搜索并快速选择项目。“
答案 0 :(得分:8)
Typeahead is removed in Bootstrap 3所以改为使用http://github.com/twitter/typeahead.js。示例:http://bootply.com/69994
var items = new Array();
$( ".dropdown-menu li a.hc" ).each(function( index ) {
items.push( $(this).text() );
});
$('.dropdown-menu input').click(function(){return false;}); //prevent menu hide
$('.typeahead').typeahead(
{
name: 'items',
local: items
}
).on('typeahead:selected', function(obj, datum) {
if($('a.hc').filter(function(index) { return $(this).text() === datum.value; }))
{
//alert('redirect to: ' + $('a.hc').filter(function(index) { return $(this).text() === datum.value; }).attr('href'));
window.location = $('a.hc').filter(function(index) { return $(this).text() === datum.value; }).attr('href');
}
});
不要忘记包含typeahead.js和一些额外的CSS(参见:http://github.com/twitter/typeahead.js)
<div class="container">
<div class="btn-group">
<button data-toggle="dropdown" class="btn btn-inverse dropdown-toggle">Inverse <span class="caret"></span></button>
<ul class="dropdown-menu">
<li><input type="text" class="typeahead"></li>
<li><a class="hc" href="#">Action</a></li>
<li><a class="hc" href="#">Another action</a></li>
<li><a class="hc" href="#">Something else here</a></li>
<li class="divider"></li>
<li><a class="hc" href="http://www.stackoverflow.com/">Stackoverflow.com</a></li>
</ul>
</div>
</div>
请参阅:http://bootply.com/66573。使用预先输入功能(http://twitter.github.io/bootstrap/2.3.2/javascript.html#typeahead)从下拉列表中选择一个项目:
function getitems()
{
var array = new Array();
$( ".dropdown-menu li a.hc" ).each(function( index ) {
array.push( $(this).text() );
});
return array;
}
$('.dropdown-menu input').click(function(){return false;}); //prevent menu hide
$('.typeahead').typeahead(
{
source: getitems,
updater: function(item){
if($('a.hc').filter(function(index) { return $(this).text() === item; }))
{
alert('redirect to: ' + $('a.hc').filter(function(index) { return $(this).text() === item; }).attr('href'));
window.location = $('a.hc').filter(function(index) { return $(this).text() === item; }).attr('href');
}
return item;}
}
);
<div class="container">
<div class="btn-group">
<button data-toggle="dropdown" class="btn btn-inverse dropdown-toggle">Inverse <span class="caret"></span></button>
<ul class="dropdown-menu">
<li><input type="text" class="typeahead"></li>
<li><a class="hc" href="#">Action</a></li>
<li><a class="hc" href="#">Another action</a></li>
<li><a class="hc" href="#">Something else here</a></li>
<li class="divider"></li>
<li><a class="hc" href="http://www.stackoverflow.com/">Stackoverflow.com</a></li>
</ul>
</div>
</div>