在pokedex项目中调用数组

问题描述 投票:0回答:1

我最近设计了一个神奇宝贝图鉴,并创建了一个包含所有神奇宝贝 ID 和类别的数组,就像这样。

const pokedex = [
{
  pokemon: ('bulbasaur'),
  dexInfo: [
    { dexName: ('bulbasaur-name') },
    { specs: ('bulbasaur-specs') },
    { desc: ('bulbasaur-desc') }
  ],
  dexNumber: ('bulbasaur-no'),
  primaryType: ('grass-one'),
  secondaryType: ('poison-two')
}
];

function turnOnPokedex() {
  console.log('turn-on')
  pokemonImage.classList.remove('hide')
  pokemonInfo.classList.remove('hide')
  pokemonTypeOne.classList.remove('hide')
  pokemonTypeTwo.classList.remove('hide')
  dexNo.classList.remove('hide')

  for (let i = 0; i < pokedex.length; i++) {
  
  }

  nextPokemon()
}

let pokemonImage = document.getElementById('pokemon')
let pokemonInfo = document.getElementById('dex-info')
let pokemonTypeOne = document.getElementById('type-one')
let pokemonTypeTwo = document.getElementById('type-two')
let dexNo = document.getElementById('dex-number')
<img id="bulbasaur" src="images/pokemon/bulbasaur.png" width="250" height="220">
<div id="bulbasaur-no"><strong>001</strong></div>
<div id="bulbasaur-name">Bulbasaur</div>
<div id="bulbasaur-specs">
  Species: Seed Pokemon<br><br>
  Height: 2'04<br><br>
  Weight: 15.2lbs(6.9kg)
</div>
<div id="bulbasaur-desc">
A strange seed was planted on<br><br> its back at birth. The plant<br><br> sprouts and grows with this<br><br> Pokémon.
<div\>
<div class="grass-one">Grass</div>
<div class="poison-two">Poison</div>

但是,每当我尝试调用此函数时,整个图鉴都会立即显示出来,而不是仅从bulbasaur开始。关于如何解决这个问题有什么想法吗?谢谢你。

javascript arrays function variables getelementbyid
1个回答
1
投票

您的 JSON 数据不应看起来像您的 HTML 标记。每个图鉴条目本质上应该相当平坦。由于神奇宝贝通常有一种或两种类型,因此将它们存储在数组中是更好的选择。

如果您想在图鉴中使用上一个/下一个按钮,则必须存储当前索引。另外,您应该避免使用 ID 属性。类名是一种更加通用的方法。

const entry = document.querySelector('.pkmn-entry');
let currentIndex = 0;

const pokedex = [{
  id: 1,
  name: 'Bulbasaur',
  species: 'Seed Pokemon',
  height: 0.7, /* meters */
  weight: 6.9, /* kg */
  description: 'A strange seed was planted on its back at birth. The plant sprouts and grows with this Pokémon',
  types: ['grass', 'poison'],
}, {
  id: 2,
  name: 'Ivysaur',
  species: 'Seed Pokemon',
  height: 1.0, /* meters */
  weight: 13.0, /* kg */
  description: 'When the bulb on its back grows large, it appears to lose the ability to stand on its hind legs.',
  types: ['grass', 'poison'],
}, {
  id: 3,
  name: 'Venusaur',
  species: 'Seed Pokemon',
  height: 2.0, /* meters */
  weight: 100.0, /* kg */
  description: 'The plant blooms when it is absorbing solar energy. It stays on the move to seek sunlight.',
  types: ['grass', 'poison'],
}];

render();

function turnOnPokedex() {
  entry.classList.toggle('hide');
}

function navigate(button) {
  const offset = button.dataset.direction === 'prev' ? -1 : 1;
  // Cycle through
  currentIndex = (currentIndex + offset + pokedex.length) % pokedex.length;
  render();
}

function render() {
  const p = pokedex[currentIndex];
  
  const resource = `${p.id.toString().padStart(4, '0')}${p.name}.png`;
  entry.querySelector('.pkmn-img').src = getAbsolutePath(resource, 'https://archives.bulbagarden.net/media/upload');
  entry.querySelector('.pkmn-img').alt = p.name;
  entry.querySelector('.pkmn-no').textContent = p.id.toString().padStart(3, '0');
  entry.querySelector('.pkmn-name').textContent = p.name;
  entry.querySelector('.pkmn-specs').innerHTML = `
    Species: ${p.species}<br />
    Height: ${metersToFeet(p.height)}<br />
    Weight: ${round(kgToLbs(p.weight), 1)} lbs
  `;
  entry.querySelector('.pkmn-desc').textContent = p.description;
  entry.querySelector('.pkmn-types').innerHTML =
    p.types
      .map(type => `<div data-type="${type}">${capitalize(type)}</div> `)
      .join('');
}

function getAbsolutePath(filename, baseUrl) {
  const hash = CryptoJS.MD5(filename.replace(/ /g, '_')).toString();
  return `${baseUrl}/${hash[0]}/${hash.substring(0, 2)}/${filename}`;
};

function capitalize(word) {
  return word[0].toUpperCase() + word.slice(1).toLowerCase();
}

function metersToFeetAndInches(meters) {
  const inches = meters * 39.3701;
  return {
    feet: Math.floor(inches / 12),
    inches: Math.round(inches % 12)
  };
}

function metersToFeet(meters) {
  const { feet, inches } = metersToFeetAndInches(meters);
  return `${feet}'${inches}"`;
}

function kgToLbs(kg) {
  return kg * 2.20462;
}

function round(n, p = 2) {
  return (e => Math.round(n * e) / e)(Math.pow(10, p));
}
.pkmn-entry .pkmn-no {
  font-weight: bold;
}

.pkmn-entry .pkmn-types div {
  display: inline-block;
}

.hide {
  display: none;
}

.pkmn-types [data-type] { padding 0.5rem; }
.pkmn-types [data-type="grass"] { background: #AFA; }
.pkmn-types [data-type="poison"] { background: #FDF; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/crypto-js/4.1.1/core.min.js" integrity="sha512-t8vdA86yKUE154D1VlNn78JbDkjv3HxdK/0MJDMBUXUjshuzRgET0ERp/0MAgYS+8YD9YmFwnz6+FWLz1gRZaw==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/crypto-js/4.1.1/md5.min.js" integrity="sha512-3sGbaDyhjGb+yxqvJKi/gl5zL4J7P5Yh4GXzq+E9puzlmVkIctjf4yP6LfijOUvtoBI3p9pLKia9crHsgYDTUQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<button type="button" onclick="turnOnPokedex()">Toggle Pokedex</button>
<div class="pkmn-entry hide">
  <img class="pkmn-img" src="" alt="Bulbasaur" width="250" height="220">
  <div class="pkmn-no">001</div>
  <div class="pkmn-name">Bulbasaur</div>
  <div class="pkmn-specs">
    Species: Seed Pokemon<br />
    Height: 2'04<br />
    Weight: 15.2lbs(6.9kg)
  </div>
  <div class="pkmn-desc">
    A strange seed was planted on its back at birth. The plant sprouts and grows with this Pokémon.
  </div>
  <div class="pkmn-types">
    <div data-type="grass">Grass</div>
    <div data-type="poison">Poison</div>
  </div>
  <div class="actions">
    <button type="button" data-direction="prev" onclick="navigate(this)">Prev</button>
    <button type="button" data-direction="next" onclick="navigate(this)">Next</button>
  </div>
</div>

© www.soinside.com 2019 - 2024. All rights reserved.