简体   繁体   English

JSON (API) 的搜索栏,需要帮助:)

[英]search-bar for JSON (API), need help:)

i am currently stuck trying to code a search-bar for an JSON fil (linked via an API link and key).我目前正在尝试为 JSON fil(通过 API 链接和密钥链接)编写搜索栏代码。 I am fairly new to coding and especially new to this field.我对编码很陌生,尤其是这个领域。

i currently cant get my function to work with onkeyup() maybe because its an async function?我目前无法让我的 function 与 onkeyup() 一起工作可能是因为它是一个异步 function? as i said im fairly new to this so idk, and I get an error for my "x.innerHTML = "" " saying "Cannot set properties of null", now i may look like an idiot here and missing something obvious but I would very much appreciate all answers:)正如我所说,我对此很陌生,所以 idk,并且我的“x.innerHTML =”“”出现错误,说“无法设置 null 的属性”,现在我在这里看起来像个白痴并且遗漏了一些明显的东西,但我会非常感谢所有答案:)

thanku for your time!谢谢你的时间!

HTML: HTML:

 <div id="søk"><input id="søkefelt" onkeyup="søk()" type="text" placeholder="Search..">
        <ul id="listHolder"></ul>
        </div>

javascript: javascript:

window.addEventListener("DOMContentLoaded", (Event) => {
async function søk() {
    const apiKey = await fetch ("nyheter.json")
    .then ((response) => response.json());

    var data = await fetch ("https://newsapi.org/v2/top-headlines?country=us&category=business&apiKey=" + apiKey[0].apikey)
    .then((response) => response.json());

    let input = document.getElementById("søkefelt").value
    input = input.toLowerCase();
    let x = document.querySelector("listHolder");
    x.innerHTML = ""
    for (let i = 0; i < data.length; i++) {
        const obj = data[i];

        if (obj.title.toLowerCase().includes(input)) {
            const elem = document.createElement("li")
            elem.innerHTML = '${obj.title} - ${author}'
            x.appendChild(elem)
        }
        
    };

        }
søk();

}); });

querySelector requires # before ids querySelector需要#在 id 之前

querySelector("#listHolder")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM