有一个储存好json数据的数组 我想通过搜索框输入的内容 来获取数据里面的数据 展现到页面上
时间: 2023-04-03 14:03:30 浏览: 63
你可以使用 JavaScript 中的 filter() 方法来筛选出符合条件的数据,然后将它们展现到页面上。具体实现方法可以参考以下代码:
// 假设你的数据数组名为 jsonData,搜索框的 ID 为 searchInput,展示数据的 ID 为 dataDisplay
const jsonData = [
{ name: '张三', age: 20, gender: '男' },
{ name: '李四', age: 25, gender: '女' },
{ name: '王五', age: 30, gender: '男' },
{ name: '赵六', age: 35, gender: '女' }
];
const searchInput = document.getElementById('searchInput');
const dataDisplay = document.getElementById('dataDisplay');
searchInput.addEventListener('input', function() {
const keyword = this.value.trim(); // 获取搜索框输入的关键词并去除首尾空格
const filteredData = jsonData.filter(function(item) {
// 使用 filter() 方法筛选出符合条件的数据
return item.name.includes(keyword) || item.age.toString().includes(keyword) || item.gender.includes(keyword);
});
// 将筛选出的数据展现到页面上
dataDisplay.innerHTML = filteredData.map(function(item) {
return `<div>${item.name},${item.age}岁,${item.gender}</div>`;
}).join('');
});
当用户在搜索框中输入关键词时,会触发 input 事件,然后我们使用 filter() 方法筛选出符合条件的数据,并使用 map() 方法将它们转换成 HTML 代码,最后使用 join() 方法将它们拼接成一个字符串,然后将这个字符串赋值给 dataDisplay 元素的 innerHTML 属性,即可展现到页面上。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)