我正在尝试为我的 Bootstrap 文本框创建一个通用的“软搜索”菜单下拉菜单,以便当用户在键盘上键入内容时,应用程序应该通过 ajax 动态查找后端 rest api 和在其正下方的动态生成的 Bootstrap 菜单中填充结果:
我使用 jquery.bind
绑定(bind) keyup
输入事件以读取输入并动态创建此下拉列表。现在,下拉菜单生成得很好,但是,我希望当用户按下“向上/向下”键时,焦点应该自动转移到下拉菜单,然后用户应该再次使用向上/向下键选择他们的选择选择该特定选项。
现在,第一部分已经实现 - 焦点转移到第一个 <li>
下拉列表中的元素。但是,向上/向下键不适用于下拉菜单。例如,在上面的例子中,当我点击向下键时,焦点没有改变,它停留在第一个元素 - “test--Foo Bar Limited”。一旦我将焦点转移到下拉菜单上,我该怎么做才能使用箭头键使下拉菜单“可导航”?我在网上搜了很多,但还没有找到解决办法。
下面是我的 keyup
代码生成此下拉列表的事件:
$("#searchbox").bind("keyup", function(e){
console.log(e.type, e.which, e.keyCode);
console.log('keycode:',e.key);
var text = $(this).val(); //+(e.key=='Backspace' ? '': e.key);
console.log('text:',text);
if (e.key=='ArrowUp' || e.key=='ArrowDown') {
//FOCUS ON THE DROPDOWN AND RETURN
e.preventDefault();
$('#thedrop li:first-child a').focus();
// setTimeout(function() {
// }, 700);
return;
}
$("#spinner").addClass('glyphicon-refresh glyphicon-spin');
//REST API CALL:
$.get("/client/search/" + text, function(data){
$("#spinner").removeClass('glyphicon-refresh glyphicon-spin');
//CREATE THE DROPDOWN
var darray = JSON.parse(data);
var drop = '<ul tabindex="1" id="thedrop" class="dropdown-menu" role="menu" aria-expanded="true" >';
for(var i=0;i<darray.length;i++){
console.log(darray[i]['ein'],'::',darray[i]['company_name']);
drop += '<li><a tabindex="-1" href="#">' + darray[i]['ein'] + '--' + darray[i]['company_name'] + '</a></li>';
}
drop += '</ul>';
var top = $('#searchbox').offset().top;
if (darray.length>0) {
$('#thedrop').remove();
$('body').append(drop);
$('#thedrop').css({
'top':top + $('#searchbox').outerHeight() ,
'left':$('#searchbox').offset().left,
});
$('#thedrop').show();
}
});
});
编辑
我查过this和 this问题,但没有一个能帮助我。他们都提议 bootstrap 已经支持向上/向下键作为下拉菜单的标准,那么我做错了什么?
最佳答案
Bootstrap 的 JS 在页面初始化时检查并生成其 JS 组件。因此,在初始化之后添加到 DOM 的新项需要是 manually instantiated。 .
为此,您需要在将其附加到 body
之后调用 $('#thedrop').dropdown()
,如下所示:
...
if (darray.length>0) {
$('#thedrop').remove();
$('body').append(drop);
$('#thedrop').dropdown(); // <-- Inserted here
$('#thedrop').css({
'top':top + $('#searchbox').outerHeight() ,
'left':$('#searchbox').offset().left,
});
$('#thedrop').show();
}
...
关于javascript - Bootstrap - 键盘无法在动态生成的文本框软搜索菜单上工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40903017/