首页 > 解决方案 > 如何从 github api 输出存储库

问题描述

我只是在学习,请不要扔西红柿)情况如下,我使用其API在Github存储库上进行搜索,当用户打印某些内容时,他会显示可能的结果(如屏幕截图所示),现在的问题是,我如何遍历输入过程中出现的列表,以便按下时 showOnPage 函数适用于每个项目?

    constructor() {
        this.client_id = 'Iv1.46288115e5c16a2f';
        this.client_secret = '25e67ed3b6da1ebf13b04de1a8a69bc227eb811f';
        this.repo_count = 2;
    }

    async getRepo(userText){

        const repoResponse = await fetch(`https://api.github.com/search/repositories?q=${userText}&client_id=${this.client_id}&client_secret=${this.client_secret}&per_page=${this.repo_count}`);
        const repo = await repoResponse.json();
        return{
            repo: repo.items
        }
    }
}

class UI {
    constructor() {
        this.displayRepo = document.getElementById('displayRepo');
    }

    showRepo(repo){
        let output = '';
        repo.forEach(function (repo) {
            output += `
             <div class="item">${repo.name}</div>
            `});
        document.getElementById('displayRepo').innerHTML = output;
    }

    showOnPage(repo){                 //<----------
        let output = '';

        repo.forEach(function (repo) {          
            output += `
             <div class="repo-list-item">
              <p class="p-list">Name: ${repo.name}</p>
              <p class="p-list">Owner: ${repo.owner.login}</p>
              <p class="p-list">Stars: ${repo.stargazers_count}</p>
              <div class="close"></div>
            </div>
            `});
        document.getElementById('displayRep').innerHTML = output;
    }

    clearProfile(){
        this.displayRepo.innerHTML = '';
    }
}

const gitRepo = new Github();
const ui = new UI();
const searchRepo = document.querySelector('.input-repo');//input
const form = document.querySelector(".autocomplete-list");//an output list when entering something into input
const item = document.querySelector(".item");//single item in list

searchRepo.addEventListener('keyup', e =>{
    const userText = e.target.value;
    if(userText !== ''){
        gitRepo.getRepo(userText).then(data => {
            ui.showRepo(data.repo);
        });
    }else{
        ui.clearProfile();
    }
});```


  [1]: https://i.stack.imgur.com/aRFfW.png

标签: javascriptgithubgithub-api

解决方案


推荐阅读