找不到页面如果搜索栏返回没有结果javascript

fquxozlt  于 2023-03-06  发布在  Java
关注(0)|答案(1)|浏览(126)

我可以在我的搜索栏上重定向,如果没有找到结果,而不是什么都没有发生??这里我的代码如下...

function openPage() {
  var x = document.getElementById("search").value;
  x = x.replace(/\b\w/g, (firstLetter) => firstLetter.toUpperCase());

  if (x === "John Doe") {
    window.open("files/johndoe.html");
  }
  if (x === "Jane Doe") {
    window.open("files/ajanedoe.html");
  }
}
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.3.0/css/all.min.css"  />

<div class="input-group">
  <input type="search" id="search" autocomplete="off" onchange="openPage()" class="form-control rounded-pill rounded-end-0 border-0 ps-4" placeholder="Search... e.g. Stan Laurel">
  <button type="button" id="button" onclick="openPage()" value="Chercher" class="btn btn-primary rounded-pill rounded-start-0 shadow-none">
    <i class="fa fa-search"></i>
  </button>
</div>
b4lqfgs4

b4lqfgs41#

我将使用eventListener和submit事件。
注我通过删除type = button将按钮更改为submit

const files = {
  "johndoe": "files/johndoe.html",
  "janedoe": "files/janedoe.html"
}
window.addEventListener("DOMContentLoaded", () => {
  document.getElementById("searchForm").addEventListener("submit", (e) => {
    e.preventDefault();
    let x = document.getElementById("search").value;
    x = x.replace(/\s+/g,"").toLowerCase();
    const file = files[x] || "files/notfound.html";
    console.log("Opening",file)
    // window.open(file)
  })
})
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.3.0/css/all.min.css" />
<form id="searchForm">
  <div class="input-group">
    <input type="search" id="search" autocomplete="off" class="form-control rounded-pill rounded-end-0 border-0 ps-4" placeholder="Search... e.g. Stan Laurel">
    <button  id="button" value="Chercher" class="btn btn-primary rounded-pill rounded-start-0 shadow-none">
    <i class="fa fa-search"></i>
  </button>
  </div>
</form>

相关问题