如何在搜索栏中设置默认搜索结果?

x0fgdtte  于 2021-09-23  发布在  Java
关注(0)|答案(1)|浏览(276)

我正在尝试使用javascript和json构建一个搜索栏。我需要搜索栏显示一些默认的搜索结果时,任何访问者访问该页面。我将该值设置为“搜索栏”,并尝试了,但直到用户删除搜索字段中的文本后,才有搜索结果。如何在用户访问页面时显示默认或预定义的搜索结果。

const search = document.getElementById("search");
const matchList = document.getElementById("match-list");

const searchWorker = async (searchText) => {
  const res = await fetch("workers.json");
  const states = await res.json();
  let matches = states.filter((state) => {
    const regex = new RegExp(`${searchText}`, "gi");
    return state.name.match(regex);
  });
  if (searchText.length === 0) {
    matches = [];
    matchList.innerHTML = "";
  }
  outputHtml(matches);
};

const outputHtml = (matches) => {
  if (matches.length > 0) {
    const html = matches
      .map(
        (match) => `<div class=" search-result">
            <a href="${match.portfolio}">
            ${match.name} - ${match.age}<br/>
            <small>Salery - ${match.salary}</small>
            </a></div>
            `
      )
      .join("");
    matchList.innerHTML = html;
  }
};
search.addEventListener("input", () => searchWorker(search.value));
<input id="search" type="search" value="sam" />
    <div id="match-list"></div>
      </div>

我的json文件:

[
{
    "name": "sam",
    "age": "26",
    "salary": "20000",
    "portfolio": "https://www.example.com/1"
},
{
    "name": "tony",
    "age": "30",
    "salary": "30000",
    "portfolio": "https://www.example.com/2"
},
{
    "name": "sam",
    "age": "24",
    "salary": "15000",
    "portfolio": "https://www.example.com/3"
}]
mrwjdhj3

mrwjdhj31#

只需运行 searchWorker(search.value); 在顶级代码中的函数。这样地:

search.addEventListener("input", () => searchWorker(search.value));
searchWorker(search.value);

这将显示输入默认值的结果。
代码笔:https://codepen.io/manaskhandelwal1/pen/ojmxrmm

相关问题