我想检测对class ='value'的更改并自动采取措施。
HTML:
<div class="s3upload form-active">
<!-- after the form is submitted,
an external lib changes the class to: -->
<div class="s3upload link-active">
下面的代码运行不会抛出错误。但是它会同时触发两个 if 语句...因此它会自动取消。
理想情况下,我可以将突变范围缩小到class属性的特定值:“ s3upload form-active”和“ s3upload link-active”
JS:
// node to observe
const picLink = $('.s3upload')[0];
const observer = new MutationObserver(function
(mutations) {
mutations.forEach(function (mutation) {
// mutations to check for:
if (mutation.attributeName === 'class') {
console.log(mutation.type), console.log("active");
$('#saver').css('display', 'block');
}
if (mutation.oldValue) {
console.log(mutation.type), console.log("removed");
$('#saver').css('display', 'none');
}
})
}
)
observer.observe(
picLink,
{
// things related to picLink to watch for changes
attributes: true,
attributeFilter: ['class'],
childList: false,
characterData: true,
attributeOldValue: true
}
)
我一直在关注这些docs / tut
https://developer.mozilla.org/en-US/docs/Web/API/MutationRecord