You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将displayCurrencies返回的coin对象传入getCoinId作为API调用参数

问题解决:将displayCurrencies中的coin对象传递给getCoinId作为API参数

现有代码的问题分析

  • displayCurrencies 函数没有返回用户点击的coin对象,你尝试用returnID返回值,但仅在点击事件里调用,没有完成向getCoinId传递值的逻辑。
  • getCoinId里通过await displayCurrencies()获取coinID是错误逻辑,displayCurrencies的作用是渲染代币列表,它不会返回用户点击的特定coin——coin是用户交互(点击)才产生的。
  • 代码里重复绑定了coinDisplay的点击事件,且returnCoin = returnID是把函数本身赋值给变量,并非获取返回的coin值,逻辑混乱。

解决方案

核心思路:用户点击某个代币元素时,直接将该coin的id传递给getCoinId函数调用,而非让getCoinId主动去获取。

修改后的完整代码

// 渲染代币列表的函数
let displayCurrencies = async () => {
  let coinsContainer = document.querySelector(`.coins`);
  try {
    let coins = await getData();
    let coinsArray = [];
    for (const coin of coins) {
      if (coinsArray.length > 20) {
        break;
      }
      coinsArray.push(coin);
      // 创建DOM元素
      let coinDisplay = createElement(`li`, `coin`);
      let coinSymbolElement = createElement(`p`, `coinSymbol`);
      let coinIDElement = createElement(`p`, `coinID`);
      // 设置内容
      coinSymbolElement.innerHTML = coin.symbol;
      coinIDElement.innerHTML = coin.id;
      // 挂载元素
      coinDisplay.append(coinSymbolElement, coinIDElement);
      coinsContainer.appendChild(coinDisplay);

      // 点击事件:调用getCoinId并传入当前coin的id
      coinDisplay.addEventListener(`click`, () => {
        openModal();
        getCoinId(coin.id); // 直接传递coin.id给getCoinId
      });
    }
  } catch (error) {
    console.log(error);
  }
};

// 获取特定代币数据的函数,接收coinId参数
let getCoinId = async (coinId) => {
  try {
    let currencyData = `https://api.coingecko.com/api/v3/coins/${coinId}`;
    let responseData = await fetch(currencyData);
    let dataOfCoins = await responseData.json();
    console.log(dataOfCoins);
    // 这里可以添加处理返回数据的逻辑,比如填充模态框内容
  } catch (error) {
    console.log('获取代币数据失败:', error);
  }
};

// 初始化渲染列表
displayCurrencies();

关键修改点

  • 移除了无用的returnID函数,直接在点击事件中调用getCoinId并传入coin.id。
  • getCoinId函数改为接收coinId参数,不再依赖displayCurrencies的返回值。
  • 清理了重复的点击事件绑定和无效的变量赋值逻辑。

内容的提问来源于stack exchange,提问作者viko randazo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.31 13:15:24