js实现搜索跳转
实现搜索跳转的基本方法
在JavaScript中实现搜索跳转功能通常涉及监听用户输入、处理搜索逻辑以及页面跳转。以下是几种常见的实现方式:
监听输入框事件并跳转
通过监听输入框的keyup或submit事件,在用户按下回车或点击搜索按钮时触发跳转。

document.getElementById('searchInput').addEventListener('keyup', function(event) {
if (event.key === 'Enter') {
const query = encodeURIComponent(this.value);
window.location.href = `/search?q=${query}`;
}
});
表单提交跳转
使用HTML表单的action属性直接提交搜索词到目标页面,无需额外JavaScript。

<form action="/search" method="GET">
<input type="text" name="q" placeholder="Search...">
<button type="submit">Search</button>
</form>
动态搜索跳转(单页应用)
在单页应用(SPA)中,可以通过前端路由实现无刷新跳转:
// 使用React Router示例
import { useNavigate } from 'react-router-dom';
function SearchBar() {
const navigate = useNavigate();
const handleSearch = (query) => {
navigate(`/search?q=${encodeURIComponent(query)}`);
};
return <input onKeyPress={(e) => e.key === 'Enter' && handleSearch(e.target.value)} />;
}
带自动补全的搜索跳转
结合第三方API(如Google Custom Search)实现自动补全后跳转:
// 使用Google Custom Search API示例
function initAutocomplete() {
const input = document.getElementById('searchInput');
const autocomplete = new google.maps.places.Autocomplete(input);
autocomplete.addListener('place_changed', () => {
const place = autocomplete.getPlace();
window.location.href = `/search?q=${encodeURIComponent(place.name)}`;
});
}
注意事项
- 对搜索词使用
encodeURIComponent处理特殊字符,避免URL解析错误。 - 移动端需考虑虚拟键盘的“搜索”按钮事件。
- 如需记录搜索历史,可通过
localStorage存储近期搜索词。
以上方法可根据具体需求选择或组合使用。






