為什麼使用innerHTML對元素新增內容後,該元素「子代」的事件監聽器失效?

問題描述

  1. <button id="alert">alert('hello world')</button>加上事件監聽器,使其被點擊後會出現 alert 訊息
  2. 透過innerHTML<div id="target">新增一個<span>標籤(不對<button id="alert">進行任何處理),但新增完畢後,點擊<button id="alert">無法出現 alert 訊息了
  3. 示範用原始碼如下:

See the Pen innerHTML destroying descendants' event listeners by Charlie (@Charlie7779) on CodePen.

原因

MDN: Setting the value of innerHTML removes all of the element’s descendants and replaces them with nodes constructed by parsing the HTML given in the string htmlString.

解決方式

createElement()搭配 appendChild()

See the Pen appendChild by Charlie (@Charlie7779) on CodePen.

MDN: The Node.appendChild() method adds a node to the end of the list of children of a specified parent node.

insertAdjacentHTML()

See the Pen insertAdjacentHTML() by Charlie (@Charlie7779) on CodePen.

關於element.insertAdjacentHTML(position, text)

See the Pen insertAdjacentHTML() -- position by Charlie (@Charlie7779) on CodePen.

參考文件