首页 > 解决方案 > 未定义的“addEventListener”

问题描述

我试图做到这一点,以便当用户单击 30 个团队中的一个时,使用 Giphy API 查询被单击的团队。

使用的 giphy API 密钥是公共 API 密钥。

// all 30 NBA Teams //
var predefinedButtons = [
  "Atlanta Hawks",
  "Boston Celtics",
  "Brooklyn Nets",
  "Charlotte Hornets",
  "Chicago Bulls",
  "Cleveland Cavaliers",
  "Dallas Mavericks",
  "Denver Nuggets",
  "Detroit Pistons",
  "Golden State Warriors",
  "Houston Rockets",
  "Indiana Pacers",
  "LA Clippers",
  "LA Lakers ",
  "Memphis Grizzlies",
  "Miami Heat",
  "Milwaukee Bucks",
  "Minnesota Timberwolves",
  "New Orleans Hornets",
  "New York Knicks",
  "Oklahoma City Thunder",
  "Orlando Magic",
  "Philadelphia Sixers",
  "Phoenix Suns",
  "Portland Trail Blazers",
  "Sacramento Kings",
  "San Antonio Spurs",
  "Toronto Raptors",
  "Utah Jazz",
  "Washington Wizards"
];
console.log(predefinedButtons);


// The Buttons added dynamically //
var $nbaTeams;

var nbaButtons = function nbaGiphy() {
  for ( i in predefinedButtons ) {
    $nbaTeams = $("<button class='.btn btn-secondary' 'onclick='getNBAGiphy()''>").text(predefinedButtons[i]);
    $("#nbaTags").append($nbaTeams);
  }

}
nbaButtons();


//  The code below is where the event listener is 'undefined'  //
function getNBAGiphy() {
  var nbaSearchGifs;
  nbaSearchGifs.addEventListener('click', function() {
    nbaSearchGifs = $(".btn btn-secondary").val();
    xhr = $.get("http://api.giphy.com/v1/gifs/search?q="+nbaSearchGifs+"&api_key=dc6zaTOxFJmzC&limit=15");
    xhr.done(function (response) {
      console.log("success got data", response);
      nbaTeamData = response.data
      $("#giphyContent").html("");
      console.log(nbaSearchGifs);
    })
  });
}
getNBAGiphy();

标签: javascriptjqueryajaxgiphy-api

解决方案


您正在声明变量,但尚未为其分配任何值。所以默认情况下它是未定义的。我指的代码是:

 function getNBAGiphy() {
    var nbaSearchGifs;
      nbaSearchGifs.addeventListner

推荐阅读