【问题标题】:using select to set a filter on api data使用 select 对 api 数据设置过滤器
【发布时间】:2020-02-12 05:10:34
【问题描述】:

在这个问题上摸不着头脑。我希望能够应用基于标签的过滤器。我正在使用 poke api 并显示数据并按 ID 排序。我想做的是让用户从标签中选择“类型”,如果口袋妖怪的话,并让页面过滤器基于它(保持排序)。如果用户不选择任何内容,它只会显示全部 150。

我提前为自己是个菜鸟道歉!

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <meta http-equiv="X-UA-Compatible" content="ie=edge" />
        <title>Quick's Pokedex</title>
        <link rel="stylesheet" href="style.css" />
        <link rel="stylesheet" href="/css/animate.css" />
        <link href="https://fonts.googleapis.com/css?family=Rubik&display=swap" rel="stylesheet"/>
        <link rel="stylesheet" href="https://pro.fontawesome.com/releases/v5.12.1/css/all.css" integrity="sha384-TxKWSXbsweFt0o2WqfkfJRRNVaPdzXJ/YLqgStggBVRREXkwU7OKz+xXtqOU4u8+" crossorigin="anonymous">
    </head>
    <body>
        <div class="header">
            <img src="/assets/img/two.png" alt="Pokemon Logo" height="500" class="animated fadeInLeftBig logo" id="logo">
        </div>
        <div class="container">
            <h3 class="full-experience">Get the full experience!    <i class="fas fa-level-down-alt"></i></h3>
            <audio class="audio-player" loop src="/assets/audio/pokemon.mp3" controls> Error: your web browser does not support this audio player. </audio>
            <h1 class="quicks-h1">Quick's Pokedex</h1>
            <div class="sorting">
                <h2>Sorting</h2>
                <p>Select at least one type</p>
                <div class="custom-select" style="width:200px;">
                    <select>
                    <option value="0">Select Type:</option>
                    <option value="1">Bug</option>
                    <option value="2">Dragon</option>
                    <option value="3">Electric</option>
                    <option value="4">Fairy</option>
                    <option value="5">Normal</option>
                    <option value="6">Psychic</option>
                    <option value="7">Fighting</option>
                    <option value="8">Water</option>
                    <option value="9">Fire</option>
                    <option value="10">Flying</option>
                    <option value="11">Ice</option>
                    <option value="12">Poison</option>
                    <option value="13">Rock</option>
                    <option value="14">Grass</option>
                    <option value="15">Ground</option>
                    </select>
                </div>
                <br>
                <div class="custom-select" style="width:200px;">
                    <select><option value="16">Sort By:</option>
                        <option value="17">Name</option>
                        <option value="18">ID</option>
                        </select>
              </div>
              <br>
              <button class="sort-btn">GO!</button>
            </div>
        <div class="pokedex-div">
            <ul class="pokedex" id="pokedex"></ul>
        </div>
    </div>
<script src="app.js"></script>
<script src="dropdown.js"></script>
    </body>
</html>

这里是 app.js 我确实尝试在底部设置过滤,但似乎无法弄清楚。

// //Main API Call//

const pokedex = document.getElementById('pokedex');
const fetchPokemon = () => {
    const promises = [];
    for (let i = 1; i <= 150; i++) {
        const url = `https://pokeapi.co/api/v2/pokemon/${i}`;
        promises.push(fetch(url).then((res) => res.json()));
    }
    Promise.all(promises).then((results) => {
        const pokemon = results.map((result) => ({
            name: result.name,
            image: result.sprites['front_default'],
            type: result.types.map((type) => type.type.name).join(', '),
            id: result.id
        })).sort((a, b) => a.id > b.id ? 1 : -1);
        displayPokemon(pokemon);
    });
};
const displayPokemon = (pokemon) => {
    const pokemonHTMLString = pokemon
        .map(
            (pokeman) => `
    <li class="card">
        <img class="card-image" src="${pokeman.image}"/>
        <h2 class="card-title">${pokeman.id}. ${pokeman.name}</h2>
        <p class="card-subtitle">Type: ${pokeman.type}</p>
    </li>
`
        )
        .join('');
    pokedex.innerHTML = pokemonHTMLString;
};
fetchPokemon();

const filterPokemon = pokemon.filter() => {
    const myDropDown = document.querySelector('#myDropDown')
}

我也有一个 dropdown.js...我怀疑有人需要它,但它就在这里:

var x, i, j, selElmnt, a, b, c;
/* Look for any elements with the class "custom-select": */
x = document.getElementsByClassName("custom-select");
for (i = 0; i < x.length; i++) {
  selElmnt = x[i].getElementsByTagName("select")[0];
  /* For each element, create a new DIV that will act as the selected item: */
  a = document.createElement("DIV");
  a.setAttribute("class", "select-selected");
  a.innerHTML = selElmnt.options[selElmnt.selectedIndex].innerHTML;
  x[i].appendChild(a);
  /* For each element, create a new DIV that will contain the option list: */
  b = document.createElement("DIV");
  b.setAttribute("class", "select-items select-hide");
  for (j = 1; j < selElmnt.length; j++) {
    /* For each option in the original select element,
    create a new DIV that will act as an option item: */
    c = document.createElement("DIV");
    c.innerHTML = selElmnt.options[j].innerHTML;
    c.addEventListener("click", function(e) {
        /* When an item is clicked, update the original select box,
        and the selected item: */
        var y, i, k, s, h;
        s = this.parentNode.parentNode.getElementsByTagName("select")[0];
        h = this.parentNode.previousSibling;
        for (i = 0; i < s.length; i++) {
          if (s.options[i].innerHTML == this.innerHTML) {
            s.selectedIndex = i;
            h.innerHTML = this.innerHTML;
            y = this.parentNode.getElementsByClassName("same-as-selected");
            for (k = 0; k < y.length; k++) {
              y[k].removeAttribute("class");
            }
            this.setAttribute("class", "same-as-selected");
            break;
          }
        }
        h.click();
    });
    b.appendChild(c);
  }
  x[i].appendChild(b);
  a.addEventListener("click", function(e) {
    /* When the select box is clicked, close any other select boxes,
    and open/close the current select box: */
    e.stopPropagation();
    closeAllSelect(this);
    this.nextSibling.classList.toggle("select-hide");
    this.classList.toggle("select-arrow-active");
  });
}

function closeAllSelect(elmnt) {
  /* A function that will close all select boxes in the document,
  except the current select box: */
  var x, y, i, arrNo = [];
  x = document.getElementsByClassName("select-items");
  y = document.getElementsByClassName("select-selected");
  for (i = 0; i < y.length; i++) {
    if (elmnt == y[i]) {
      arrNo.push(i)
    } else {
      y[i].classList.remove("select-arrow-active");
    }
  }
  for (i = 0; i < x.length; i++) {
    if (arrNo.indexOf(i)) {
      x[i].classList.add("select-hide");
    }
  }
}

/* If the user clicks anywhere outside the select box,
then close all select boxes: */
document.addEventListener("click", closeAllSelect);\

【问题讨论】:

    标签: javascript html api filter


    【解决方案1】:

    electric 类型过滤,例如:

    const pokedex = document.getElementById('pokedex');
    const fetchPokemon = () => {
      const promises = [];
      for (let i = 1; i <= 150; i++) {
        const url = `https://pokeapi.co/api/v2/pokemon/${i}`;
        promises.push(fetch(url).then((res) => res.json()));
      }
      Promise.all(promises).then((results) => {
        const pokemon = results.map((result) => ({
          name: result.name,
          image: result.sprites['front_default'],
          type: result.types.map((type) => type.type.name).join(', '),
          id: result.id
        })).sort((a, b) => a.id > b.id ? 1 : -1);
        console.log('sadfa',pokemon)
        const filteredPokemonsByType= pokemon.filter(x=>x.type==='electric');
        console.log('Filtered by eletric', filteredPokemonsByType);
    
      });
    };
    
    fetchPokemon()

    这是您的下拉列表的完整示例:https://jsfiddle.net/fkq43gbu/

    【讨论】:

    • 如果我想通过 html 中的下拉菜单设置排序怎么办?
    猜你喜欢
    • 1970-01-01
    • 2013-10-25
    • 1970-01-01
    • 1970-01-01
    • 2020-01-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-04
    相关资源
    最近更新 更多