JS 实现input输入完后 自动查询
时间: 2023-06-20 21:08:35 浏览: 54
可以通过监听 input 元素的 `input` 事件,当输入框内容发生变化时触发该事件,然后在事件处理函数中进行查询操作。示例代码如下:
```javascript
const inputEl = document.getElementById('input-id');
const resultEl = document.getElementById('result-id');
inputEl.addEventListener('input', () => {
const inputValue = inputEl.value.trim();
if (inputValue) {
// 发起查询请求
fetch(`https://api.example.com/search?q=${inputValue}`)
.then(response => response.json())
.then(data => {
// 处理查询结果
resultEl.textContent = JSON.stringify(data);
})
.catch(error => {
console.error(error);
});
} else {
// 清空查询结果
resultEl.textContent = '';
}
});
```
以上代码中,通过 `getElementById` 方法获取输入框和结果展示元素的引用,然后通过 `addEventListener` 方法监听输入框的 `input` 事件,在事件处理函数中获取输入框的值并进行查询操作,最后将查询结果展示在结果展示元素中。