当我单击引导下拉菜单时,我试图将焦点集中在输入字段上,可以看到事件在触发创建的警报的情况下触发,但是焦点没有移到搜索框。谁能看到原因?
startScan()
$("#devSearch").keyup(function() {
filter = $("#devSearch").val().toUpperCase()
div = $("#devDropdown")
a = div.find("a")
for (i = 0; i < a.length; i++) {
if (a[i].innerHTML.toUpperCase().indexOf(filter) > -1) {
a[i].style.display = "";
} else {
a[i].style.display = "none";
}
}
});
$("#devDD").click(function(){
alert('yes')
$('#devSearch').focus();
});
答案 0 :(得分:1)
您可以使用shown.bs.dropdown代替点击事件:
$("#devDD").on('shown.bs.dropdown', function(e){
$('#devSearch').focus();
});
此外,您需要将 id =“ devDD” 移至父 li 元素。
您更新的fiddle
$("#devSearch").keyup(function() {
filter = $("#devSearch").val().toUpperCase()
div = $("#devDropdown")
a = div.find("a")
for (i = 0; i < a.length; i++) {
if (a[i].innerHTML.toUpperCase().indexOf(filter) > -1) {
a[i].style.display = "";
} else {
a[i].style.display = "none";
}
}
});
$("#devDD").on('shown.bs.dropdown', function(e){
$('#devSearch').focus();
});
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css">
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js"></script>
<ul class="nav nav-tabs">
<li class="nav-item">
<a class="nav-link active" href="#">Active</a>
</li>
<li class="nav-item dropdown" id="devDD">
<a class="nav-link dropdown-toggle" data-toggle="dropdown" href="#" role="button" aria-haspopup="true" aria-expanded="false">Devices</a>
<div class="dropdown-menu dropdown-menu-fixed-height" id="devDropdown">
<input class="form-control form-control-sm" type="text" placeholder="Search..." id="devSearch" style="width:8rem; margin:0 1rem">
<a class="dropdown-item" href="#">All Entires</a>
<a class="dropdown-item" href="#">Big bob</a>
<a class="dropdown-item" href="#">Little bob</a>
<a class="dropdown-item" href="#">Sausage</a>
<a class="dropdown-item" href="#">Chicken</a>
<span class="filter-results no-results">Oops, nothing found!<span>
</div>
</li>
</ul>
答案 1 :(得分:0)
在输入已完全呈现为DOM中的交互之前,似乎触发了focus()
事件。如果将超时添加到函数中,它将解决该超时问题。
$('#devDD').click(function() {
setTimeout(function() {
$('#devSearch').focus();
}, 150);
});
或者,由于搜索框是唯一的输入,因此可以使用autofocus属性:
<input class="form-control form-control-sm" type="text"
placeholder="Search..." id="devSearch" style="width:8rem;
margin:0 1rem" autofocus>