jQuery搜索自动提示是一种前端交互功能,它允许用户在输入框中输入内容时,实时显示与输入内容相关的建议列表。这种功能通常用于提高用户体验,减少用户输入时间,并帮助用户快速找到所需信息。
以下是一个简单的基于静态数据的jQuery搜索自动提示示例:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>jQuery Search Autocomplete</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js"></script>
<link rel="stylesheet" href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
</head>
<body>
<input type="text" id="search-box">
<ul id="suggestions"></ul>
<script>
$(document).ready(function() {
var data = ["Apple", "Banana", "Cherry", "Date", "Elderberry", "Fig", "Grape"];
$("#search-box").on("input", function() {
var input = $(this).val().toLowerCase();
$("#suggestions").empty();
if (input.length > 0) {
var filteredData = data.filter(function(item) {
return item.toLowerCase().indexOf(input) > -1;
});
$.each(filteredData, function(index, value) {
$("#suggestions").append("<li>" + value + "</li>");
});
}
});
$(document).on("click", function(event) {
if (!$(event.target).closest("#search-box").length) {
$("#suggestions").empty();
}
});
});
</script>
</body>
</html>
通过以上内容,您应该对jQuery搜索自动提示有了全面的了解,并能够解决一些常见问题。
领取专属 10元无门槛券
手把手带您无忧上云