实现搜索条件和搜索内容固定,以及回车键搜索跳转
1.写出搜索条件和搜索框
<form class="parent">
<select id="searchSelect" style="border: 1px solid #325da7;border-right: none;" value="resource">
<option value="resource">资源名称</option>
<option value="user">作者名称</option>
</select>
<input type="text" class="search" placeholder="搜索" id="searchtxt" />
<input type="button" id="selectBtn" class="btn" />
</form>
2.添加scss样式
.parent {
margin-top: 10px;
display: flex;
flex-wrap: nowrap;
.search {
width: 448px;
height: 36px;
outline: none;
border: 1.5px solid #325da7;
}
.btn {
height: 40px;
width: 60px;
background: #325da7 url('https://www.ydwenku.com/master/images/searchico.png') center center no-repeat;
background-size: 35px;
border: none;
}
}
页面
3.搜索框选择条件,在搜索框中输入内容,然后进行页面跳转
let selectedValue = 'resource';
const searchSelectElement = document.getElementById("searchSelect"); //搜索框条件选择下拉框
const searchInputElement = document.getElementById("searchtxt"); //搜索输入框
const selectBtnElement = document.getElementById("selectBtn"); //搜索按钮
searchSelectElement.addEventListener("change", searchSelect);
searchInputElement.addEventListener("input", handleSearchInput);
searchInputElement.addEventListener("keypress", handleSearchKeyPress);
function handleSearchKeyPress(event) {
if (event.key === "Enter") {
event.preventDefault(); // 阻止默认行为
openSearchPage(searchInputElement.value);
}
}
function handleSearchInput(event) {
const searchText = event.target.value;
selectBtnElement.onclick = function () {
openSearchPage(searchText);
};
}
function openSearchPage(searchText) {
const url = `/html/searchpage/search.html?searchText=${searchText}&selectSearch=${selectedValue}`;
window.open(url);
}
在搜索框中输入内容,然后进行页面跳转
4.页面跳转后从地址栏中获取相关数据,搜索条件和搜索框中的内容
const urlsearch = new URLSearchParams(location.search);
const serchname = urlsearch.get("searchText"); //获取地址栏中传递的参数
const serChange = urlsearch.get("selectSearch");
$('#searchtxt').val(serchname);
$('#searchSelect').val(serChange)
从地址栏中获取到相关数据searchText和selectSearch的值
$('#searchtxt').val(serchname); // 搜索框中条件固定
$('#searchSelect').val(serChange) // 搜索框中搜索内容固定