首頁  >  文章  >  web前端  >  如何檢測 DOM 中的屬性變更?

如何檢測 DOM 中的屬性變更?

Patricia Arquette
Patricia Arquette原創
2024-10-26 16:59:03409瀏覽

How can I detect Attribute Changes in the DOM?

偵測DOM 中的屬性變更

問題:

問題:

是否可以啟動事件,例如是否可以啟動事件,例如是否可以啟動事件,例如是否可以啟動事件,例如自訂事件,當HTML 元素的屬性發生變更時?更具體地說,當圖像 (如何檢測 DOM 中的屬性變更?) 元素的 src 屬性或分區 (

) 元素的 innerHTML 屬性被修改時?

答案:

突變事件(已棄用)

歷史上,DOM 突變事件用於監視屬性變更。然而,它們自 2012 年以來已被棄用。建議使用它們的替代品 MutationObserver。

MutationObserver

MutationObserver 是一個進階 API,使您能夠觀察 DOM 的變更。它提供比突變事件更細粒度的控制,並允許您追蹤特定元素、突變和樹結構。

<code class="javascript">// Create a new MutationObserver instance
const observer = new MutationObserver((mutationsList) => {
  for (const mutation of mutationsList) {
    // Check if the mutation is an attribute change
    if (mutation.type === "attributes") {
      console.log(`Attribute changed on ${mutation.target.nodeName}`);
    }
  }
});

// Start observing the document body for attribute changes
observer.observe(document.body, { attributes: true });</code>

MutationObserver 範例:

jQuery 事件外掛程式

jQuery 的。它為基本用例提供了更易於使用的 API。

<code class="javascript">$("img").on("attrchange", (e) => {
  console.log(`Image src changed to ${e.target.src}`);
});</code>

jQuery 突變事件外掛範例:

注意: 瀏覽器對DOM 突變事件的支持各不相同。始終建議在依賴此功能之前檢查相容性。

以上是如何檢測 DOM 中的屬性變更?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn