简体   繁体   中英

Can't add an event listener to an element from an API

I am building a trivia webapp using an API and i want to add an event listener to the button with the correct answer so that when the user clicks it it will display a message saying they're right and it'll get a new question. Here's how the code looks:

function useApiData(triviaObj) {
  let answers = sortArrayRandomly([
    triviaObj.results[0].correct_answer,
    triviaObj.results[0].incorrect_answers[0],
    triviaObj.results[0].incorrect_answers[1],
    triviaObj.results[0].incorrect_answers[2],
  ]);

  document.querySelector("#category").innerHTML = `Category: ${triviaObj.results[0].category}`;
  document.querySelector("#difficulty").innerHTML = `Difficulty: ${triviaObj.results[0].difficulty}`;
  document.querySelector("#question").innerHTML = `Question: ${triviaObj.results[0].question}`;

  document.querySelector("#answer1").innerHTML = `${answers[0]}`;
  document.querySelector("#answer2").innerHTML = `${answers[1]}`;
  document.querySelector("#answer3").innerHTML = `${answers[2]}`;
  document.querySelector("#answer4").innerHTML = `${answers[3]}`;

  let rightAnswer = triviaObj.results[0].correct_answer;
  rightAnswer.addEventListener("click", correctAnswer);

  console.log(answers);
}

function correctAnswer() {
  alert("correct");
  getTrivia();
}

It tells me that the AddEventListener is not a function, how can I fix this?

Event listeners go on DOM elements, not on pieces of data or other variables. Try finding the correct answer element and attaching the event listener to that:

const rightAnswer = triviaObj.results[0].correct_answer;
const matchingAnswer = answers.find((x) => x === rightAnswer);
const rightElement = Array.from(document.querySelectorAll('*[id^="answer"]'))
  .find((el) => el.innerText.includes(rightAnswer))
rightElement.addEventListener("click", correctAnswer);

Use a loop to fill in the answer elements. In that loop you can check if the current answer is the correct answer and add the event listener.

 answers.forEach((answer, i) => { let button = document.querySelector(`#answer${i+1}`); button.innerHTML = answer; if (answer == triviaObj.results[0].correct_answer) { button.addEventListener("click", correctAnswer); } else { button.removeEventListener("click", correctAnswer); } });

Assuming that triviaObj.results[0].correct_answer is a number representing the correct answer, then:

Replace

let rightAnswer = triviaObj.results[0].correct_answer;

with

let rightAnswer = document.querySelector(`#answer${triviaObj.results[0].correct_answer}`);

This is much more simple than Zan Anger's solution.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM