最近维护一个老项目,需要监听input框搜索然后下拉选择,今天就分享一下
1.html代码:
<div class="td-search"><input type="text" id="searchInput">
<div id="searchResults"></div>
</div>
2.css代码
<style>
.td-search {
position: relative;
}
.d-search {
position: absolute;
top: 49px;
left:15px;
background: white;
border: 1px solid #000 !important;
}
.search-result {
border-bottom: 1px solid #e3e3e3 !important;
padding: 10px ;
cursor: pointer;
}
</style>
3.js部分
$(function () {
$("#searchResults").hide();
$('#searchInput').on('input', function () {
var searchValue = $(this).val();
if (searchValue.length >= 1) {
$.ajax({
url: '/search',
method: 'POST',
data: { key: searchValue, sessionToken: sessionToken },
success: function (response) {
// 清空之前的搜索结果
$('#searchResults').empty();
$("#searchResults").show();
// 生成新的搜索结果
$.each(response.data, function (index, result) {
let item = `<div class="search-result"
data-id='${result.userId}'>${result.name}-${result.mobile}</div>`;
$('#searchResults').append(item);
});
},
error: function (error) {
console.log(error);
}
});
} else {
$('#searchResults').html('');
}
});
$(document).on('click', '.search-result', function () {
var resultValue = $(this).text();
let bindUserId=$(this).data("id");
$('#searchInput').val(resultValue);
$('#searchResults').html('');
$("#searchResults").hide();
});
});
这段代码中,使用jQuery的on方法来绑定input事件监听器。在监听器中,我们获取用户输入的值,并向服务器发送一个Ajax请求。在响应成功的回调函数中,我们使用empty方法清空之前的搜索结果,然后使用each方法遍历服务器返回的结果数组,生成新的搜索结果。在响应错误的回调函数中,我们输出错误信息。