0

我是编码新手,我遇到了 EventListener 的问题。我添加了一个事件侦听器,它最初不是在 HTML 文件中,因为我在 js 文件中创建了它。所以我使用 GIPHY API 来获取 Suggested Gifs EndPoint。当有人在显示建议结果的下拉栏上写字时,我的目标是当我单击其中一个结果时,它会自动搜索该结果。代码看起来像这样:

//Get Suggested Gifs

function autoComplete() {
  let searchInput = document.getElementById('input')
  let inputValue = searchInput.value
  let searchTerm = inputValue.replace(' ', '+') //Replaces the spaces with an '+' because the API request it
  let suggestedGifsUrl = `http://api.giphy.com/v1/gifs/search/tags?api_key=e50H7kadOO3wsBzSsJ1YpQL9cEjMglfi&q='${searchTerm}'&limit=3`
  fetch(suggestedGifsUrl)
    .then(response => response.json())
    .then(dataSearch => {
      let searchResults = document.getElementById('searchresults')
      searchResults.style.display = 'block'
      searchResults.innerHTML = ''
      if (dataSearch.data.length > 0) {
        for (let i = 0; i < 3; i++) {
          let results = document.createElement('li')
          results.classList.add('results')
          searchResults.appendChild(results)
          let textResult = dataSearch.data[i].name ? dataSearch.data[i].name : null
          results.innerHTML = ''
          results.innerHTML = textResult
        }
      } else {
        searchResults.style.display = 'none'
      }

    })
    .catch(err => console.log(err))
}

//Search AutoComplete Results
function searchAutocomplete(textResult) {
  let url = `https://api.giphy.com/v1/gifs/search?api_key=e50H7kadOO3wsBzSsJ1YpQL9cEjMglfi&q=${textResult}&limit=20` //Fetch API w/ the Suggested Values
  fetch(url)
    .then(response => response.json())
    .then(response => {
      let dataObject = response.data
      showGifs(dataObject) //Calling function showGifs()
    })
    .catch(err => console.log(err))
}

document.getElementsByClassName('results')[0].addEventListener('click', searchAutocomplete(textResult))
document.getElementsByClassName('results')[1].addEventListener('click', searchAutocomplete(textResult))
document.getElementsByClassName('results')[2].addEventListener('click', searchAutocomplete(textResult))


function showGifs(dataObject) {
  let container = document.getElementById("gif-container");
  container.innerHTML = ""; //Deletes everything that was inside the '#gif-container' div
  let i = 0
  let data = dataObject
  dataObject.forEach(img => {
    let div = document.createElement('div');
    div.classList.add("gif-box");
    let hashtagHover = document.createElement('div');
    hashtagHover.classList.add("gif-hashtags");
    hashtagHover.setAttribute('style', 'height: 295px');
    let gifImg = document.createElement('img');
    let title = document.createElement('h4');
    gifImg.setAttribute('src', img.images.original['url']);
    console.log(gifImg);
    div.appendChild(gifImg);
    div.appendChild(title);
    hashtagHover.appendChild(div);
    container.appendChild(hashtagHover);
    let hashtags = data[i].title;
    let hashtagsArray = hashtags.split(' ');
    title.innerHTML = '#' + hashtagsArray[0] + ' #' + hashtagsArray[1] + ' #' + hashtagsArray[2]
    i++
  })
}
<div class="inputsearch" id="search-form">
  <input type="text" name="texto" id="input" placeholder="Busca gifs, hashtags, temas, busca lo que quieras…">
  <div class="search" id='search'>
    <img src="/assets/combined_shape.svg" alt="search_icon">
    <p>Buscar</p>
  </div>
</div>
<ul class="searchresults" id="searchresults"></ul>

当我运行代码时,控制台会记录一个错误:“Uncaught TypeError: Cannot read property 'addEventListener' of undefined”,我尝试了很多东西,但没有任何效果。如果有人可以帮助我,我将不胜感激!!

4

0 回答 0