我的代码工作正常,但问题是我无法找到如何在不点击输入按钮或提交按钮的情况下显示搜索结果的解决方案。我的意思是,当用户开始在搜索输入字段中输入内容时,我想显示 JSON 文件中的搜索结果。有人可以帮忙吗?我将不胜感激。谢谢
我尝试过的代码。
const result = document.getElementById('result');
const userAction = async(event) => {
event.preventDefault();
fetch('https://jsonplaceholder.typicode.com/todos')
.then(response => response.json())
.then(todos => {
todos.forEach((todo) => {
result.innerHTML = `${todo.userId} ${todo.id} ${todo.title} ${todo.completed}`;
});
})
}
<form method="POST">
<input type="text" id="searchName" class="form-control" placeholder="Lorem name">
<button onclick="searchAction(event)" class="search-icon"><img src="images/search-icon.svg" alt="submit"></button>
</form>
<div class="dropbox">
<p id="list"></p>
</div>
最佳答案
通过使用input event ,每次在输入字段中按下按键(或发生其他更改)时,您都可以运行代码。
上面链接中的示例代码:
const input = document.querySelector('input');
const log = document.getElementById('values');
input.addEventListener('input', updateValue);
function updateValue(e) {
log.textContent = e.target.value;
}
请注意,通过使用此功能,您将在每次按键时进行一次 AJAX 调用。由于这可能会向服务器发送太多无用的请求,因此您可能需要构建一些缓存或速率限制功能(例如,如果一秒钟没有按下任何键,则仅获取数据)。
关于javascript - 如何在不按回车按钮或提交按钮的情况下输入时获取搜索结果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58629007/