ZBLOG

const observer = new MutationObserver((mutationsList) => { for (let mutation of mutationsList) { // 当某个属性被修改时触发 if (mutation.type === 'attributes') { console.log(`属性 '${mutation.attributeName}' 已被修改`); ...

在您提供的代码中,MutationObserver 监听属性变更,并且在检测到某个特定属性(如 data-example)被修改时,您又手动将其值改回旧值。这会导致递归调用,因为当您使用 setAttribute 恢复旧值时,又会触发 MutationObserver 的回调函数,造成无限循环。

为了解决这个问题,可以采取以下几种方法:

  1. 禁用观察者:在恢复旧值之前,先停止观察,然后再恢复值,再重新启用观察器。
  1. const observer = new MutationObserver((mutationsList) => {
  2. for (let mutation of mutationsList) {
  3. if (mutation.type === 'attributes') {
  4. console.log(`属性 '${mutation.attributeName}' 已被修改`);
  5. console.log('旧值:', mutation.oldValue);
  6. if (mutation.attributeName === 'data-example') {
  7. const newValue = targetNode.getAttribute('data-example');
  8. // 如果新的值不符合预期,可以将其改回旧值(如用 oldValue)
  9. if (newValue !== "expected value") {
  10. observer.disconnect(); // 停止观察
  11. targetNode.setAttribute('data-example', mutation.oldValue);
  12. console.log('已恢复为旧值:', mutation.oldValue);
  13. observer.observe(targetNode, { attributes: true, attributeOldValue: true }); // 重新开始观察
  14. }
  15. }
  16. }
  17. }
  18. });
  19. // 开始观察目标节点
  20. observer.observe(targetNode, { attributes: true, attributeOldValue: true });
  1. 添加标志位:通过设置一个标志位来避免重复操作。
  1. let isRestoring = false;
  2. const observer = new MutationObserver((mutationsList) => {
  3. for (let mutation of mutationsList) {
  4. if (mutation.type === 'attributes' && !isRestoring) {
  5. console.log(`属性 '${mutation.attributeName}' 已被修改`);
  6. console.log('旧值:', mutation.oldValue);
  7. if (mutation.attributeName === 'data-example') {
  8. const newValue = targetNode.getAttribute('data-example');
  9. // 如果新的值不符合预期,可以将其改回旧值(如用 oldValue)
  10. if (newValue !== "expected value") {
  11. isRestoring = true; // 设置标志位
  12. targetNode.setAttribute('data-example', mutation.oldValue);
  13. console.log('已恢复为旧值:', mutation.oldValue);
  14. isRestoring = false; // 重置标志位
  15. }
  16. }
  17. }
  18. }
  19. });
  20. // 开始观察目标节点
  21. observer.observe(targetNode, { attributes: true, attributeOldValue: true });

以上两种方法都可以有效地避免递归调用的问题。选择适合您的具体应用场景的方法即可。


内容由零声教学AI助手提供,问题来源于学员提问

本站部分文章来源于网络,版权归原作者所有,如有侵权请联系站长删除。
转载请注明出处:https://golang.0voice.com/?id=19210

分享:
扫描分享到社交APP
上一篇
下一篇
发表列表
游客 游客
此处应有掌声~
评论列表

还没有评论,快来说点什么吧~

联系我们

在线咨询: 点击这里给我发消息

微信号:3007537140

上班时间: 10:30-22:30

关注我们
x

注册

已经有帐号?