簡體   English   中英

addEventListener()不執行

[英]addEventListener() does not execute

--------------------------------------------更新:10分鍾后- --------------------------------------------------

經過評論后,我認為有必要提供更多contxt信息,說明該問題方法的調用位置。

//fetch fake user info from RandomAPI
fetch('https://randomuser.me/api/?results=12&nat=us') //pull 12 results
    //parse json
    .then(response => response.json()) 
    //process employee data and return a new employee list
    .then(data => extractEmployeeData(data.results)) 
    //for every employee in the list, generate dom element and bind it to employee object
    .then(employees => employees.map((employee, index) => employee.generateEmployeeCard(main, index)))
    .catch(error => console.log(error));

話雖如此...我真的不知道該錯誤是否與異步調用有關...也許您有經驗的人會找到任何線索...

-------------------------------------------------- -原始帖子----------------------------------------------- ---------------

我有一堂課:

class Employee {
  this.card;
  this.info = { some employee info... }

  ......

  // generates employee card and binds handler to the dom object generated
  generateEmployeeCard(containerDiv, index) {
      const html = ` some markup... `
      containerDiv.innerHTML += html;
      this.card = document.getElementById(`employee${index}`);

      //THE PROBLEM LINE
      this.card.addEventListener('click', event => this.generateEmployeeModal());
  }

  .......
}

一切都會按預期進行,直到generateEmployeeCard()方法的最后一行為止。 這行代碼應該將事件偵聽器添加到dom元素對象“ this.card”中。 但是相反,此行選擇在執行時不執行任何操作。 在執行此行之后,我查看了“事件監聽器”選項卡。 這看起來真的很奇怪,我在這里找不到任何類似的問題。 請幫忙,謝謝!

您應該將事件處理程序直接分配給該函數:

this.card.addEventListener("click", this.generateEmployeeModal);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM