我有用于搜索建议的 Jquery 代码,
HTML 代码:
<div class="search-section">
<div class="search-inner">
<input type="text" name="search" class="search_input">
<input type="hidden" class="redirectUrl">
<button type="button" class="btn-redirect">Search</button>
</div>
<div class="dropdown-section">
<ul class="dropdown-list">
</ul>
</div>
</div>
Jquery 代码:
const allConstList = ['John','Micheal','Allen','Jarvis'];
$(document).on('keyup change','.search_input',function(e) {
const inpVal = e.target.value;
const $dropdownSection = $(e.target).parent().parent().find('.dropdown-section');
$dropdownSection.empty();
$dropdownSection.show();
for(const constId in allConstList){
const constName = allConstList[constId];
if(constName.toLowerCase().includes(inpVal.toLowerCase()))
$dropdownSection.append(`<li class="dropdown-list-item" data-title="${constName}">${constName}</li>`);
}
});
$('body').click('.dropdown-list-item',function(e) {
const title = e.target.getAttribute('data-title');
$(e.target).parent().parent().find('.search_input').val(title);
$(e.target).parent().parent().find('.dropdown-section').hide();
});
在这里我必须点击 .dropdown-list-item
两次,第一次点击什么也没有发生。
请帮忙,提前致谢