<body>
<input type="text" class="ivu-input" />
<button onclick="search()" class="search">搜索</button>
<script>
// 发送请求---被搜索的数组
// fetch方法
var date;
fetch("https://api.apiopen.top/api/getImages?type=animal&page=1&size=10")
.then((response) => response.json())
.then((res) => {
date = res.result.list;
});
// 定义搜索函数
function query(list, keyWord, attribute = "name") {
const reg = new RegExp(keyWord); // 创建正则表达式
const arr = [];
for (let i = 0; i < list.length; i++) {
if (reg.test(list[i][attribute])) {
arr.push(list[i]);
}
}
// 返回搜索结果
return arr;
}
// 获取button
var button = document.getElementsByClassName("search")[0];
console.log(button);
if (button) {
// 监听button
button.addEventListener("click", function () {
// 获取输入框的值
var input = document.getElementsByClassName("ivu-input")[0].value;
// 调用搜索函数
let list = query(date, input, "title");
console.log(list);
});
}
</script>
</body>
搜索结果: