js-数据筛选
html:
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title></title> <link rel="stylesheet" href="./css/data.css" /> </head> <body> <h1>排行榜</h1> <input type="text" / placeholder="输入搜索内容" oninput="seach(value)"> <table> <thead> <tr> <th> 排序 </th> <th> 姓名 </th> <th onclick="sort()"> 交易量 </th> </tr> </thead> <tbody> </tbody> </table> <script src="js/datas.js"> </script> </body> </html>
css:
* { margin: 0; padding: 0; } h1 { width: 100%; height: 60px; line-height: 60px; text-align: center; } input { margin-left: 85%; border: 0; } table { width: 100%; } td, th { height: 50px; text-align: center; } .div{ font-size: 20px; font: 900; }
js:
let data; let xhr = new XMLHttpRequest(); xhr.open('get', './js/data.json', true); xhr.send(); xhr.onreadystatechange = function() { if (xhr.readyState == 4 && xhr.status == 200) { data = JSON.parse(xhr.responseText); console.log(data); apply(data); } }; function apply(data) { let str = ``; for (let i = 0; i < data.length; i++) { str += `<tr> <td>${i+1}</td> <td>${data[i].name}</td> <td>${data[i].data}</td> </tr>` } if (data.length == 0) { str += `<tr> <td></td> <td class="div">暂无数据</td> <td></td> </tr>` document.getElementsByTagName('tbody')[0].innerHTML = str; } else { document.getElementsByTagName('tbody')[0].innerHTML = str; } } function sort() { if (sessionStorage.getItem('name') == 1) { data.sort((a, b) => a.data - b.data); sessionStorage.removeItem('name'); } else { data.sort((a, b) => b.data - a.data); sessionStorage.setItem('name', '1'); } apply(data); } function seach(target) { let arr = []; for (let i = 0; i < data.length; i++) { console.log(data[i].name); if (data[i].name.indexOf(target) >= 0 || String(data[i].data).indexOf(target) >= 0) { arr.push(data[i]); } } apply(arr); }