使用数组迭代方法渲染页面数据并进行简单的查询
一、页面预览
二、需求分析
-
将data里的数据动态渲染到页面上
data = [ { id:1, pname:"小米", price:3999 }, { id:2, pname:"华为", price:7999 }, { id:3, pname:"三星", price:9999 }, { id:4, pname:"oppo", price:6999 }, { id:5, pname:"vivo", price:5999 }, ]
-
筛选出指定价格范围内的商品
三、基本思路
- 使用forEach()方法遍历data数组,生成对应的表格,并将数据展示在表格中
- 使用filter()方法筛选出对应的数据,封装到一个新数组里;遍历新数组,生成对应的表格,并将数据重新展示在表格中
四、相关代码
-
页面结构
<div class="search"> <label for="">按价格查询:</label> <input type="text" class="start"> - <input type="text" class="end"> <button class="sousuo">搜索</button> </div> <table> <thead> <tr> <th>id</th> <th>产品名称</th> <th>价格</th> </tr> </thead> <tbody> <!-- --> </tbody> </table>
-
功能代码
<script> var data = [ { id:1, pname:"小米", price:3999 }, { id:2, pname:"华为", price:7999 }, { id:3, pname:"三星", price:9999 }, { id:4, pname:"oppo", price:6999 }, { id:5, pname:"vivo", price:5999 }, ]; let that = null; class Find{ constructor(){ that = this; // 获取tbody this.tbody = document.querySelector("tbody"); //获得数组 this.data = data; // // 获取起始价格的表单 构造函数只会在页面刷新时执行一次,无法动态获取表单里的数据 // this.star = document.querySelector(".start"); // // 获取最高价的表单 // this.end = document.querySelector(".end"); // 获取搜索按钮 this.button1 = document.querySelector(".sousuo"); //页面渲染时先获取所有数据 this.setData(data); //搜索方法 this.button1.onclick = this.find; } // 设置搜索按钮的点击方法 find(){ // 每次点击都可以实时获得输入框的值 let star = document.querySelector(".start").value; let end = document.querySelector(".end").value; console.log(star); console.log(end); const newData = that.data.filter((item,index,array)=>{ return item.price >= star && item.price <= end }); if(newData.length){ that.setData(newData); }else{ // 简单设置一个查询异常情况 let error = [{id:"没有查询到指定商品"}]; that.setData(error); } } // 页面渲染时先获取所有数据 setData(myData){ // 先清空列表数据,再渲染 that.tbody.innerHTML = ""; myData.forEach((item,index,arr)=>{ that.tbody.innerHTML += ` <tr> <th>${arr[index].id}</th> <th>${arr[index].pname}</th> <th>${arr[index].price}</th> </tr> `; }) } } // 创建一个实例对象 let find = new Find(); </script>