繁体   English   中英

如何使用 JavaScript 过滤 Json 文件中的结果?

[英]How to filter result in Json file using JavaScript?

如果在 json 文件中找不到标题,我对如何显示错误感到有些困惑。这是我尝试过的代码。 一切正常,但是当我使用 if(searchName.= todo.name) 时,无论名称是写还是错误,结果都只显示错误。请帮助我。我将不胜感激。

const list = document.getElementById('list');
const userAction = async (event) => {
  event.preventDefault();
  const searchName = document.getElementById('searchName').value.trim();
  fetch('https://jsonplaceholder.typicode.com/todos')
  .then(response => response.json())
  .then(todos => {
    todos.forEach((todo) => {
      if(searchName == todo.title){
        const li = document.createElement('li'); 
        li.textContent = `${todo.userId} ${todo.id} ${todo.title} ${todo.completed}`;
        list.appendChild(li);
      } else if(searchName != todo.title)
{
 const li = document.createElement('li');
   list.textContent = `Search Result not found`;
 list.appendChild(li);

}
    });
  })
}

<form method="POST">
 <input type="text" id="searchName" class="form-control" placeholder="Lorem name">
<button  onclick="userAction(event)" class="search-icon"><img src="images/icon.png" alt="submit"></button>
  </form>

<ul id="list">

</ul>

像这样的东西。

 const list = document.getElementById('list'); const userAction = async (event) => { event.preventDefault(); const searchName = document.getElementById('searchName').value.trim(); fetch('https://jsonplaceholder.typicode.com/todos').then(response => response.json()).then(todos => { let result = todos.filter((todo) => todo.title.includes(searchName)); while (list.firstChild) { list.removeChild(list.firstChild); } if (result.length > 0) { result.forEach(todo => { const li = document.createElement('li'); li.textContent = `${todo.userId} ${todo.id} ${todo.title} ${todo.completed}`; list.appendChild(li); }); } else { // not found. } }); }
 <form method="POST"> <input type="text" id="searchName" class="form-control" placeholder="Lorem name"> <button onclick="userAction(event)" class="search-icon"><img src="images/icon.png" alt="submit"></button> </form> <ul id="list"> </ul>

const td = todos
  .filter(element => element.contain(searchName))
  .map((todo) => {
        const li = document.createElement('li'); 
        li.textContent = `${todo.userId} ${todo.id} ${todo.title} ${todo.completed}`;
        list.appendChild(li);
  })
if(td.length <= 0) {
  const li = document.createElement('li');
  list.textContent = `Search Result not found`;
  list.appendChild(li);
}

或更花哨的方法:

const td = todos
  .filter(element => element.contain(searchName))
  .map((todo) => `${todo.userId} ${todo.id} ${todo.title} ${todo.completed}`)
if(td.length <= 0) {
    td[0] = `Search Result not found`
}
td.forEach(t => list.append(`<li> ${t}</li>`))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM