我正在尝试创建一个类似功能的下拉菜单,一旦有人开始在输入框中输入内容,就会显示一个 div。我可以在单个元素上附加鼠标单击事件以选择它们。但是我无法通过按回车键来选择它们。
HTML
<input type="text" class="input" name="example" id="example" placeholder="example..." autocomplete="off" list="examplelist" />
<div class="autofill">
<ul class="autocomplete">
<li class="autocomplete-list">John Doe (San Jose, CA)</li>
<li class="autocomplete-list">Jane Doe (San Francisco, CA)</li>
<li class="autocomplete-list">John Jane (San Carlos, CA)</li>
</ul>
</div>
JQuery
$(document).ready(function () {
var $listItems = $('li.autocomplete-list'),
$div = $('div.autofill'),
$input = $('#example');
$div.hide();
$('input#example').on('keydown', function (e) {
var key = e.keyCode,
$selected = $listItems.filter('.selected'),
$current;
$div.show();
if (key != 40 && key != 38) return;
$listItems.removeClass('selected');
if (key == 40) { // Down key
if (!$selected.length || $selected.is(':last-child')) {
$current = $listItems.eq(0);
} else {
$current = $selected.next();
}
} else if (key == 38) { // Up key
if (!$selected.length || $selected.is(':first-child')) {
$current = $listItems.last();
} else {
$current = $selected.prev();
}
}
$current.addClass('selected');
// When I press enter after selecting the li element
// Does not work :(
$current.on('keypress keydown keyup', 'li', function (event) {
if (event.keyCode == 13) {
var value = $(this).text().split('(')[0].trim();
$input.val(value) ;
$div.hide();
}
});
});
// If somebody clicks on the li item
$('li.autocomplete-list').on('click', function (e) {
var value = $(this).text().split('(')[0].trim();
$input.val(value);
$div.hide();
});
// change color on hover
$('li.autocomplete-list').hover(
function(){ $(this).addClass('hover') },
function(){ $(this).removeClass('hover') }
);
// When I press enter after selecting the li element
// Does not work :(
$('li.autocomplete-list').on('keypress keydown keyup', 'li', function (event) {
if (event.keyCode == 13) {
var value = $(this).text().split('(')[0].trim();
$input.val(value) ;
$div.hide();
}
});
});
如何选择一个特定的 li 元素,然后在按下 enter 时获取它的值?这是 JSFiddle
最佳答案
<li>
元素没有焦点,即使它是在视觉上选择的。文本输入仍然具有焦点。
您需要检查文本 <input>
上的回车键.不在<li>
$('input#example').on('keydown', function (e) {
//...
var key = e.keyCode
if (key == 40) { // Down key
//...
} else if (key == 38) { // Up key
//...
} else if (key == 13) { // Enter key
//... make sure $current is not null
}
//...
}
还要注意这个语句
if (key != 40 && key != 38) return;
当按下回车键时,将从事件处理程序返回。
这是一个 fiddle :http://jsfiddle.net/q1vtwtdp/4/
关于javascript - 链接 jquery keydown 事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30065428/