【发布时间】:2019-10-26 13:12:39
【问题描述】:
如果在 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>
【问题讨论】:
-
你不需要
if(searchName != todo.title)它在第一个 if 条件中隐含 -
使用
todos.filter(element => element.contain(searchName));更好 -
@MahdyAslamy 你能告诉我如何在我的代码中使用这个。Thnaks
-
@JacekRojek 不工作仍然只显示错误但不显示结果。即使我写了正确的标题。
标签: javascript html json rest