我有這個<div>隨機變化的元素。例如,有時是這樣的:
<td class="Disabled activeClass" title="disable"></td>
有時是這樣的:
<td class="Enabled activeClass" title="Enable"></td>
例如,我可以每 15 分鐘執行一次 Ajax 請求,以提醒我元素是否發生更改而不重新加載整個頁面?
這是我嘗試過的:
$.ajax({
type: 'POST',
data: 'gofor="Enabled activeClass',
url: 'ajax.php',
success: function(response) {
ClassName("Enabled activeClass").html(response);
}
});
我對這些東西有點陌生,所以請放輕松。
uj5u.com熱心網友回復:
我假設這是您要解決的問題:
- 您想要一種能夠了解頁面上元素的更改并對其做出反應的方法。
你在問:
- 我可以從頁面發出 Ajax 請求,以觀察同一頁面上的元素是否已更改。
如果這是正確的,那么您的問題的答案是否定的。
Ajax 請求用于后端呼叫。您不能進行 Ajax 呼叫來獲取呼叫 Ajax 呼叫的頁面,并讓它觀察對其的更改。您的 Ajax 請求可能能夠獲取相同的頁面,但它將是來自服務器的該頁面的新副本,而不是瀏覽器當前顯示的頁面實體。
相反,要觀察 DOM(當前頁面)的特定元素的變化并能夠對該變化做出反應,您需要使用MutationObserver. 它正如它的名字所說的那樣:觀察一個 DOM 元素的變化。
為了做到這一點:
- 定義目標
MutationObserver
const targetNode = document.querySelector('div.active');
- 定義
MutationObserver. 這描述了觀察者應該觀察什么。在這種情況下,我們想要
const observerOptions = {
// Observe only the "class" attribute
attributeFilter: ['class'],
// Record the previous value of the "class" attribute
// so we can show on the console log
attributeOldValue: true,
// Observe only the target node
// and ignore changes to children nodes of the target node.
subtree: false
}
- 為
MutationObserver. 觀察者在觀察到目標的變化時呼叫此函式。
function mutationCallback(mutationList, observer) {
// TODO: Implement this
}
- 創建
MutationObserver,傳遞回呼函式。
const observer = new MutationObserver(mutationCallback);
- 開始觀察,傳遞目標和選項。
observer.observe(targetNode, observerOptions);
- 在某些時候,當您想要停止對目標的觀察更改時,您可以斷開觀察者的連接。
observer.disconnect();
例子
div以下是單擊 a 時更新a 的示例button。單擊時button,它會呼叫toggleDiv()更改div的類和標題屬性以及div.
然后我創建了一個MutationObserver來獨立檢查對div. 此觀察者僅觀察. div在觀察到變化時,它會呼叫回呼函式mutationCallback()。
function toggleDiv() {
const el = document.querySelector('div.active');
const isDisabled = el.classList.contains('disabled');
if (isDisabled) {
el.classList.replace('disabled', 'enabled');
el.setAttribute('title', 'enabled');
el.innerText = 'Enabled';
} else {
el.classList.replace('enabled', 'disabled');
el.setAttribute('title', 'disabled');
el.innerText = 'Disabled';
}
}
function mutationCallback(mutationList, observer) {
mutationList.forEach((mutation) => {
if (mutation.type === 'attributes') {
console.log(`The ${mutation.attributeName} attribute has changed from '${mutation.oldValue}' to '${mutation.target.classList}'`);
}
});
}
const targetNode = document.querySelector('div.active');
const observerOptions = {
// Observe only the "class" attribute
attributeFilter: ['class'],
// Record the previous value of the "class" attribute
attributeOldValue: true,
// Observe only the target node. Ignore changes to children nodes of the target node.
subtree: false
}
const observer = new MutationObserver(mutationCallback);
observer.observe(targetNode, observerOptions);
<div class="disabled active" title="disabled">Disabled</div>
<br/>
<button onclick="toggleDiv()">Toggle div</button>
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/521589.html
