【问题标题】:API Data not showing up in Bootstrap 5 modalAPI 数据未显示在 Bootstrap 5 模式中
【发布时间】:2021-10-05 11:30:34
【问题描述】:

所以我有一个 Pokemon API 并通过 .fetch() 构建了前端,我想创建另一个模式来显示代码一些统计信息。我已经获得了要连接的 Bootstrap 模式,但我无法从 API 获取数据以进入第二个模式。似乎我的代码根本没有与第二个模态连接。这是一个代码笔,因为这个项目太大,无法在此处发布。

API 链接: https://pokeapi.co/api/v2/pokemon/?limit=150

代码笔: https://codepen.io/drxl/pen/OJmZJQZ

这是我试过的JS:

     //loads the stats for 2nd modal

   function loadStats(item) {
      let url = item.detailsUrl;
      return fetch(url).then(function (response) {
         return response.json();
      }).then(function (details) {
         //add details to stats
         item.stats = [];
         for (var i = 0; i < details.stats.length; i++) {
            item.stats.push(details.stats[i].stat.name);
         }
         item.stats = item.stats.join('<br>');

      }).catch(function (e) {
         console.error(e);
      });
   }

    function loadStatDetails(item) {
      pokemonRepository.loadStats(item).then(function () {
         showStatModal(item);
      });
   }
   function showStatModal(item) {
      pokemonRepository.loadStats(item).then(function () {
         // eslint-disable-next-line no-undef
         let StatmodalBody = $(".Statmodal-body");
         // eslint-disable-next-line no-undef
         let StatmodalTitle = $(".Statmodal-title");

         //clears previous content in modal
         StatmodalTitle.empty();
         StatmodalBody.empty();

         //create elenebtb for pokemon name
         // eslint-disable-next-line no-undef
         let nameElement = $("<h1>" + item.name + "</h1>");

         //add stats
         let statsElement = $("<p>" + item.stats + "<p>");

         StatmodalTitle.append(nameElement);
         StatmodalBody.append(statsElement);

         $('#my-Statmodal').modal('show');

      });
   }


   return {
      add: add,
      getAll: getAll,
      addListItem: addListItem,
      loadList: loadList,
      loadDetails: loadDetails,
      showDetails: showDetails,
      loadStats: loadStats,
      loadStatDetails: loadStatDetails,
   };

【问题讨论】:

  • 什么在调用loadStatDetails 函数?为什么调用pokemonRepository.loadStats(item) 两次?
  • 我不知道我是菜鸟
  • 检查下面的asnwer,它现在在第二个模态中加载统计数据
  • 不用担心@NamelessDude21。我们都是从某个时候开始的。

标签: javascript jquery bootstrap-modal fetch-api bootstrap-5


【解决方案1】:

更新的 JS 代码:

let pokemonRepository = (function () {
    let pokemonList = [];
    let apiUrl = 'https://pokeapi.co/api/v2/pokemon/?limit=150';
    let searchInput = document.querySelector("#searchIn");
 
    function add(pokemon) {
       pokemonList.push(pokemon);
    }
 
    function getAll() {
       return pokemonList;
    }
 
    function addListItem(pokemon) {
       let pokeUl = document.querySelector('.list-group');
       let listItem = document.createElement('li');
       let button = document.createElement('button');
       let baseStatsButton = document.querySelector('#base-stats-button');
       button.innerText = pokemon.name;
       button.classList.add('btn');
       button.classList.add('btn-primary');
       listItem.classList.add('group-list-item');
       button.setAttribute("data-target", "#my-modal");
       button.setAttribute("data-toggle", "modal");
       listItem.appendChild(button);
       pokeUl.appendChild(listItem);
       button.addEventListener('click', function () {
          showDetails(pokemon)
       });
       baseStatsButton.addEventListener('click', function(){
        showStatModal(pokemon);
       });
    }
 
 
    function loadList() {
       return fetch(apiUrl).then(function (response) {
          return response.json();
       }).then(function (json) {
          json.results.forEach(function (item) {
             let pokemon = {
                name: item.name,
                detailsUrl: item.url
             };
             add(pokemon);
          });
       }).catch(function (e) {
          console.error(e);
       })
    }
 
    function loadDetails(item) {
       let url = item.detailsUrl;
       return fetch(url).then(function (response) {
          return response.json();
       }).then(function (details) {
          //Add details to item
          item.imageUrl = details.sprites.front_default;
          item.imageUrlBack = details.sprites.back_default;
          item.height = details.height / 10;
          item.weight = details.weight / 10;
          // pokemon types
          item.types = [];
          for (var i = 0; i < details.types.length; i++) {
             item.types.push(details.types[i].type.name);
          }
          item.types = item.types.join(',  ');
          //pokemon abilities
          item.abilities = [];
          // eslint-disable-next-line no-redeclare
          for (var i = 0; i < details.abilities.length; i++) {
             item.abilities.push(details.abilities[i].ability.name);
          }
          item.abilities = item.abilities.join(',  ');
 
       }).catch(function (e) {
          console.error(e);
       });
    }
 
    //loads the stats for 2nd modal
 
    function loadStats(item) {
       let url = item.detailsUrl;
       return fetch(url).then(function (response) {
          return response.json();
       }).then(function (details) {
          //add details to stats
          item.stats = [];
          for (var i = 0; i < details.stats.length; i++) {
             item.stats.push(details.stats[i].stat.name);
          }
          item.stats = item.stats.join('<br>');
       
       }).catch(function (e) {
          console.error(e);
       });
    }
 
 
    function showDetails(item) {
       pokemonRepository.loadDetails(item).then(function () {
         console.log("item:",item);
          showModal(item);
       });
    }
 
    function showModal(item) {
       pokemonRepository.loadDetails(item).then(function () {
          // eslint-disable-next-line no-undef
          let modalBody = $(".modal-body");
          // eslint-disable-next-line no-undef
          let modalTitle = $(".modal-title");
 
          //clears previous content in modal
          modalTitle.empty();
          modalBody.empty();
 
          //create elenebtb for pokemon name
          // eslint-disable-next-line no-undef
          let nameElement = $("<h1>" + item.name + "</h1>");
 
          //create img element
          // eslint-disable-next-line no-undef
          let imageElementFront = $('<img class="modal-img" style="width:50%">');
          imageElementFront.attr("src", item.imageUrl);
          // eslint-disable-next-line no-undef
          let imageElementBack = $('<img class="modal-img" style="width:50%">');
          imageElementBack.attr("src", item.imageUrlBack);
 
          //create element for pokemon height 
          // eslint-disable-next-line no-undef
          let heightElement = $("<p>" + "Height: " + item.height + "m</p>");
 
          //for pokemon weight
          let weightElement = $("<p>" + "Weight: " + item.weight + "kgs</p>");
          //pokemon types
          // eslint-disable-next-line no-undef
          let typesElement = $("<p>" + "Types: " + item.types + "</p>");
 
          //pokemon abilities 
          // eslint-disable-next-line no-undef
          let typesAbilities = $("<p>" + "Abilities: " + item.abilities + "</p>");
 
 
          //eventlistener to for search  bar
          searchInput.addEventListener('input', function () {
             let listPokemon = document.querySelectorAll('.group-list-item');
             let value = searchInput.value.toUpperCase();
 
             listPokemon.forEach(function (pokemon) {
                if (pokemon.innerText.toUpperCase().indexOf(value) > -1) {
                   pokemon.style.display = '';
                } else {
                   pokemon.style.display = 'none'
                }
             })
          });
 
          modalTitle.append(nameElement);
          modalBody.append(imageElementFront);
          modalBody.append(imageElementBack);
          modalBody.append(heightElement);
          modalBody.append(weightElement);
          modalBody.append(typesElement);
          modalBody.append(typesAbilities);
 
 
          // eslint-disable-next-line no-undef
          $('#my-modal').modal('toggle');
       });
    }
 
 
 
    function loadStatDetails(item) {
       pokemonRepository.loadStats(item).then(function () {
          showStatModal(item);
       });
    }
    function showStatModal(item) {
       pokemonRepository.loadStats(item).then(function () {
          // eslint-disable-next-line no-undef
          let StatmodalBody = $(".Statmodal-body");
          // eslint-disable-next-line no-undef
          let StatmodalTitle = $(".Statmodal-title");
 
          //clears previous content in modal
          StatmodalTitle.empty();
          StatmodalBody.empty();
 
          //create elenebtb for pokemon name
          // eslint-disable-next-line no-undef
          let nameElement = $("<h1>" + item.name + "</h1>");
 
          //add stats
          let statsElement = $("<p>" + item.stats + "<p>");
 
          StatmodalTitle.append(nameElement);
          StatmodalBody.append(statsElement);
 
          $('#my-Statmodal').modal('show');
 
       });
    }
 
 
    return {
       add: add,
       getAll: getAll,
       addListItem: addListItem,
       loadList: loadList,
       loadDetails: loadDetails,
       showDetails: showDetails,
       loadStats: loadStats,
       loadStatDetails: loadStatDetails,
    };
 
    })();

出了什么问题? 您的 Show stats 按钮需要一个点击处理程序来加载 api 数据并显示相同的数据。

【讨论】:

  • @namelessdude21 发现了这个bug,给我一点时间把它放在这里
  • 当我进入第二个模式时,它会遍历所有名称,我不希望这样,我希望它保留在我点击的名称上
  • 您要求的是解决方案,而不是不推荐的问题@RDX10290
猜你喜欢
  • 2021-03-19
  • 2021-08-04
  • 1970-01-01
  • 2022-12-21
  • 2023-01-17
  • 2019-01-14
  • 2021-06-11
  • 1970-01-01
  • 2017-09-20
相关资源
最近更新 更多