[英]Simple JS search function for website doesn't work anymore
我在我的网站上使用 JS 放置了一个简单的搜索功能,但它似乎不再起作用了——它在周末之前运行良好,但我认为这是因为我放入了太多的“if”参数。对于例如,客户将搜索 XLR,它会在同一页面上重新加载 XLR 类别。
这是我的代码:
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, height=device-height, initial-scale=1.0, user-scalable=0, minimum-scale=1.0, maximum-scale=1.0">
<title>Tuto</title>
</head>
<body style=" background-color: rgb(4, 41, 255);">
<input type="search" value="" id="search" onchange="openPage()">
<script>
function openPage() {
var x = document.getElementById("search").value;
if (x === "Oyaide") {
window.location.replace("/Products#!/oyaide/sort/manual");
}
if (x === "oyaide") {
window.location.replace("/Products#!/oyaide/sort/manual");
}
if (x === "OYAIDE") {
window.location.replace("/Products#!/oyaide/sort/manual");
}
if (x === "Opus") {
window.location.replace("/Products#!/opus-collection/sort/manual");
}
if (x === "opus") {
window.location.replace("/Products#!/opus-collection/sort/manual");
}
(以此类推,大约有 50 个条目)
我需要将它们分组为变量吗? 我刚刚列出
您的问题可能是打字错误,并且绝对超出了您的代码段。 我只想向您展示一种更简单的方法来使用地图/对象在搜索值和 URL 之间进行映射:
const sites = {
'oyaide': '/Products#!/oyaide/sort/manual',
'opus': '/Products#!/opus-collection/sort/manual',
// ...
};
function openPage() {
const x = document.getElementById("search").value;
if(sites[x.toLowerCase()] != null) {
window.location.replace(sites[x.toLowerCase()]);
}
}
但即使这样也不是最优的,我强烈建议您使用建议的结果制作一个简单的搜索功能,例如谷歌就是这样做的。 它很容易实现,用户不必输入整个单词就可以通过这种方式获得结果。
在您的页面上,更改
<input type="search" value="" id="search" onchange="openPage()">
到
<input type="search" id="search" />
在您的<script>
,添加以下内容:
document.addEventListener('DOMContentLoaded', function() {
document.getElementById('search').addEventListener('change', openPage);
})
出于各种原因,使用内联事件侦听器被认为是不当行为。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.