【发布时间】:2023-03-18 13:13:01
【问题描述】:
我试图检测 <li> 的值何时发生变化,然后通过添加背景颜色将类添加到 li。
我有这个开关:
mutationList.forEach((mutation) => {
switch(mutation.type) {
case 'childList':
$(this).css('background-color','red');
console.log('childlist edited');
break;
case 'attributes':
console.log('attr edited')
break;
}
});
但是颜色没有添加到背景中。然而,我得到了大量的控制台日志,如下所示:
(66) 个子列表已编辑
(2) 子列表已编辑
(14) 个子列表已编辑
(81) 子列表已编辑
这就是我想要发生的事情:
1)当li的值发生变化时,运行一个函数
2) 该函数将清除所有 li 中的所有 css,然后将 background-red 添加到刚刚编辑的 li。
function onTimerElapsed() {
var next = Math.floor(Math.random() * jQuery('#stuff ul li').length - 1);
if (next === -1) {
next = 0;
}
var nextLi = document.querySelectorAll('#stuff ul li')[next];
var id = nextLi.attributes["id"].value;
$('#' + id).text(Math.floor(Math.random() * 1150));
var targetNode = document.querySelector("#stuff ul");
var observerOptions = {
childList: true,
attributes: true,
subtree: true //Omit or set to false to observe only changes to the parent node.
}
var observer = new MutationObserver(callback);
observer.observe(targetNode, observerOptions);
}
function callback(mutationList, observer) {
mutationList.forEach((mutation) => {
switch(mutation.type) {
case 'childList':
console.log('childlist edited')
break;
case 'attributes':
console.log('attr edited')
break;
}
});
}
$(document).ready(function() {
setInterval(onTimerElapsed, 4000);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h1>Detect Dom change</h1>
<div id="stuff">
<ul>
<li class="total" id="t1">1453</li>
<li class="total" id="t2">523</li>
<li class="total" id="t3">54643</li>
<li class="total" id="t4">2324</li>
<li class="total" id="t5">56476</li>
<li class="total" id="t6">3434</li>
</ul>
</div>
【问题讨论】:
-
"Jsfiddle: jsfiddle.net/josz492m" 请更新您的问题以使用 Stack Snippets (
[<>]工具栏按钮),而不仅仅是链接到它。链接失效,人们不应该去场外帮助你。 Here's how to do one. -
你在说什么,我添加了代码:剩下的只是为了演示而实际更改 dom。
-
@Mark - 没必要粗鲁。正如我上面所说,我正在谈论将您的 runnable 示例 in 放在问题中,而不是将其留在场外。它让人们更容易帮助你,这肯定是你的目标吗?
-
@T.J.Crowder 我怎么粗鲁了?我添加 JSFiddle 链接的原因是因为它需要额外的库,并且大多数人都要求提供 jsfiddle 链接。
-
@Mark - “你在说什么”当有人礼貌地要求你做某事并且清楚它是什么时,这是不礼貌的。外部库不是问题,而且要求 jsFiddles 的人只是过时了——他们真正想要的是一个可运行的示例,最好在现场提供(在 95% 的情况下)。
标签: javascript mutation-observers