I have this function to get data from an API, then I create a <div>
and set the data into that . After that, for each <div>
I created, I set a “click” event for that <div>
.
The code worked fine for the first time I clicked a <div>
, but after that, the “click” event cannot be triggered anymore, I haven’t found the reason, can someone help me?
Thank you, below is the src:
const setSuggestedQuestion = async function () {
if (!hasSetSuggestedQuestions) {
/* Get data from the API, response is like this:
["Question 1","Question 2"]
*/
await getSuggestedMessage()
hasSetSuggestedQuestions = true
//Create the div, then set the necessary data for it
const suggestedDiv = document.getElementsByClassName("mc_suggested_question")[0]
for (let i = 0; i < suggestedQuestion.data[0].length; i++) {
const suggestedQuestionDiv = document.createElement('div')
suggestedQuestionDiv.className = "detail_suggested_question";
suggestedQuestionDiv.setAttribute("data_suggested_question", suggestedQuestion.data[0][i])
suggestedQuestionDiv.innerHTML = generateChatElement(link, 9, suggestedQuestion.data[0][i], '');
suggestedDiv.appendChild(suggestedQuestionDiv);
}
//Set click event the all of the created div
const suggestedElements = document.getElementsByClassName("detail_suggested_question");
for (let suggestedElement of suggestedElements) {
suggestedElement.addEventListener("click", async function () {
sendQuestion(this.getAttribute("data_suggested_question"))
});
}
}
I get the data, set it into a block, then set a click event for it
I expect the event will be fired anytime I click the block, but it runs only once