首页 > 解决方案 > 如何在一个函数中为不同的按钮添加多个事件监听器?

问题描述

const nbaLoads = () => {
  fetch('nba.json')
  .then(res => res.json())
  .then(data => {

    let output = '';

    data.forEach(s => {
        if(s.year === parseInt(select.value)){
         output += `
        <img src="" width= 100px; height=100px>
        <h4>CHAMPIONS: ${s.champion}</h4>
      `
    } if(s.year === parseInt(select.value)){
        output += `
        <img src="" width= 100px; height=100px>
        <h4>RUNNER UP: ${s.runnerUp}</h4>
      `
    }
    });
    document.querySelector('#output').innerHTML = output;
  })
};

champion.addEventListener('click', nbaLoads);
runnerUp.addEventListener('click', nbaLoads);

如果我点击冠军按钮,我的结果是冠军和亚军。如果我点击亚军按钮,结果是一样的,如何更改?当我点击冠军按钮时,我想看到冠军,当我点击亚军时,我想看到亚军。

提前致谢

标签: javascriptaddeventlistener

解决方案


您在两个按钮单击时调用相同的函数。您需要提供一个参数来指示您应该设置什么类型的信息innerHTML,或者创建两个不同的函数。

第一个解决方案:

const nbaLoads = (type) => {
  fetch('nba.json')
  .then(res => res.json())
  .then(data => {

    let output = '';

    data.forEach(s => {
        if(s.year === parseInt(select.value) && type == "champions"){
         output += `
        <img src="" width= 100px; height=100px>
        <h4>CHAMPIONS: ${s.champion}</h4>
      `
    } if(s.year === parseInt(select.value) && type == "runnerUp"){
        output += `
        <img src="" width= 100px; height=100px>
        <h4>RUNNER UP: ${s.runnerUp}</h4>
      `
    }
    });
    document.querySelector('#output').innerHTML = output;
  })
};

champion.addEventListener('click', () => nbaLoads("champions"));
runnerUp.addEventListener('click', () => nbaLoads("runnerUp"));

第二种解决方案:

const nbaLoads = () =>
  fetch('nba.json')
  .then(res => res.json());

const loadChampion = () =>
  nbaLoads()
  .then(data => {
    let output = '';

    data.forEach(s => {
      if (s.year === parseInt(select.value)) {
        output += `
        <img src="" width= 100px; height=100px>
        <h4>CHAMPIONS: ${s.champion}</h4>
      `;
      }
    });

    document.querySelector('#output').innerHTML = output;

  });

const loadRunnerUp = () =>
  nbaLoads()
  .then(data => {
    let output = '';

    data.forEach(s => {
      if (s.year === parseInt(select.value)) {
        output += `
        <img src="" width= 100px; height=100px>
        <h4>RUNNER UP: ${s.runnerUp}</h4>
      `;
      }

      document.querySelector('#output').innerHTML = output;

    });
  });

champion.addEventListener('click', loadChampion);
runnerUp.addEventListener('click', loadRunnerUp);

推荐阅读