javascript 使用按钮从API加载数据后,如何执行搜索功能?

enyaitl3  于 2023-08-02  发布在  Java
关注(0)|答案(1)|浏览(72)

任务是在HTML上以表格格式显示响应,并制作一个搜索框来搜索表中的数据沿着排序功能。
数据获取的负载,但搜索功能不工作。
我需要单击该按钮,它会加载数据并相应地执行搜索。

var items = []

const load = async () => {
    try {
        const response = await fetch('https://jsonplaceholder.typicode.com/posts')
        const data = await response.json()
        items = data
        display(data)
    } catch (error) {
        document.getElementById('demo').innerHTML = `Error: ${error}`
    } 
    search();
}

const display = (data) =>{
    var table = "";
    for (var i = 0; i < data.length; i++) {
        var rowData ="<tr><td>"+data[i].userId+"</td><td>"+data[i].id+"</td><td>"+data[i].title+"</td><td>"+data[i].body;
        table+= rowData;  
    }
    document.getElementById("table").innerHTML = table;
}

// Search Function
const search = () =>{
    const table = document.getElementById('table');
    const mySearchField = document.getElementById('mySearchField');
    // const searchCharacters = []

    mySearchField.addEventListener('keyup', (e) => {
        const searchString = e.target.value.toLowerCase();
        const filteredItems = items.filter((data) => {
            console.log(data)
            return (
                data.body.toLowerCase.includes(searchString) ||
                data.title.toLowerCase.includes(searchString)
            )
        });
        display(filteredItems);
    });
}

个字符

ndasle7k

ndasle7k1#

您需要在Search函数中进行以下更改(在使用toLowerCase()函数时添加**()括号**)。它应该解决搜索问题。

return (
        data.body.toLowerCase().includes(searchString) ||
        data.title.toLowerCase().includes(searchString)
       )

字符串
整个函数看起来像这样:

// Search Function
const search = () =>{
    const table = document.getElementById('table');
    const mySearchField = document.getElementById('mySearchField');
    // const searchCharacters = []
    mySearchField.addEventListener('keyup', (e) => {
        const searchString = e.target.value.toLowerCase();

        const filteredItems = items.filter((data) => {
            console.log('11',data, searchString)
            return (
                data.body.toLowerCase().includes(searchString) ||
                data.title.toLowerCase().includes(searchString)
            )
        });
        display(filteredItems);
    });
}

相关问题