1,先在html页面构建一个输入框(输入框要绑定onchange事件)
<input type="datalist" id="inp" onchange="out()">
2,再创建一个<ul>标签便于将查询到的内容显示在<ul>标签中
1. <ul id="ul"> 2. <li>XXXX</li> 3. </ul>
3,在js中获取这两个标签中并引用json假数据
let data; let ul = document.getElementById('ul'); let inp = document.getElementById('inp') let arr = new XMLHttpRequest(); arr.open('GET', 'js/new_file.json'); arr.send(); arr.onreadystatechange = function() { if (arr.readyState == 4 && arr.status == 200) { let at = arr.responseText; data = JSON.parse(at); } }
4,通过onchange事件进行查询
function out() { let str = ''; let input = inp.value; for (let i = 0; i < data.length; i++) { if (data[i].name.indexOf(input) > -1) { str += '<li>' + data[i].name + '</li>' } } ul.innerHTML = str;