JS写一个查询功能
时间: 2023-08-19 16:10:23 浏览: 42
好的,查询功能通常需要一个输入框和一个按钮,用户在输入框中输入关键词,点击按钮后,页面会返回相应的查询结果。以下是一个简单的示例代码:
HTML部分:
```html
<input type="text" id="search-input">
<button id="search-btn">查询</button>
<div id="result"></div>
```
JS部分:
```javascript
const searchBtn = document.getElementById('search-btn');
const searchInput = document.getElementById('search-input');
const resultDiv = document.getElementById('result');
searchBtn.addEventListener('click', function() {
const keyword = searchInput.value;
// 发送查询请求,获取数据
const data = getDataByKeyword(keyword);
// 渲染查询结果
renderResult(data);
});
function getDataByKeyword(keyword) {
// 在这里编写发送请求的代码,比如使用ajax发送请求到后端API
// 返回数据
const data = [
{title: '文章标题1', content: '文章内容1'},
{title: '文章标题2', content: '文章内容2'},
{title: '文章标题3', content: '文章内容3'}
];
return data;
}
function renderResult(data) {
resultDiv.innerHTML = '';
if (data.length > 0) {
for (let i = 0; i < data.length; i++) {
const item = data[i];
const div = document.createElement('div');
div.innerHTML = `<h3>${item.title}</h3><p>${item.content}</p>`;
resultDiv.appendChild(div);
}
} else {
resultDiv.innerHTML = '没有查询到相关结果';
}
}
```
此示例代码中,点击查询按钮后,会获取输入框中的关键词,并调用 `getDataByKeyword` 函数发送查询请求,返回数据后,调用 `renderResult` 函数渲染查询结果。在 `renderResult` 函数中,会先清空之前的查询结果,然后根据返回的数据渲染结果,如果没有查询到相关结果,则显示提示信息。
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)