【问题标题】:How to observe child divs of a parent div using Mutation observer如何使用 Mutation Observer 观察父 div 的子 div
【发布时间】:2020-07-27 13:24:10
【问题描述】:

我正在尝试使用突变观察器观察父 div 下子 div 属性的变化,但不知何故我不能。到目前为止,这是我的代码。

index.html

<div id="Otp_verify_errors">
  <div class="successText" id="email_success" style="display:none" aria-hidden="true" role="alert" aria-label="E-mail address verified. You can now continue.">E-mail address verified. You can now continue.</div>
  <div class="errorText error" id="email_fail_retry" style="display: inline;" aria-hidden="true" role="alert" aria-label="Code Incorrect" aria-live="polite">Code Incorrect</div>
  <div class="errorText error" id="email_fail_no_retry" style="display:none" aria-hidden="true" role="alert" aria-label="no retry available">no retry available</div>
</div>

myIndex.js:(在 document.ready() 函数内)

所有 div 在页面启动时设置为aria-hidden:true,并且仅在按钮单击时将其中一个 div 值设置为 false,以便可以显示网页。

const verifyErrors = document.querySelector("#Otp_verify_errors");
if (verifyErrors) {
  console.log("inside mutation if"); - > I can see this in the console
  const errorObserver = new MutationObserver(function(mutations) {
    console.log(`Mutations: ${mutations}`);
    mutations.forEach(function(mutation) {
      // idea is to get the id of the div where the style attribute
      // aria-hidden is set to false dynamically based on the response 
      // from API call
    });
  });

  errorObserver.observe(verifyErrors, {
    childList: true,
    attributes: true,
    subTree: true,
    characterData: true,
  });
}

目前,即使按钮单击时样式属性发生更改,也不会跟踪任何更改。

有人可以帮我看看我在这里缺少什么吗?

【问题讨论】:

  • 错字:subTree 应该是subtree
  • @wOxxOm 感谢您帮助我。它帮助解决了问题

标签: javascript html css mutation-observers


【解决方案1】:

设法解决了问题。 另外,感谢@wOxxom 帮助我找到代码中的错误

const verifyErrors = document.querySelector("#Otp_verify_errors");
        if (verifyErrors) {
          const errorObserver = new MutationObserver(function (mutations) {
            mutations.forEach(function (mutation) {
              var attrHidden = mutation.target.getAttribute("aria-hidden");
              if (attrHidden == "false") {
                console.log(mutation.target.id);
                // do whatever you want to do with the id
              }
            });
          });

          errorObserver.observe(verifyErrors, {
            childList: true,
            attributes: true,
            subtree: true,
            characterData: true,
          });
        }

【讨论】:

    猜你喜欢
    • 2011-03-15
    • 1970-01-01
    • 2014-03-11
    • 2010-11-09
    • 1970-01-01
    • 2016-03-20
    • 2012-08-24
    • 2017-05-04
    相关资源
    最近更新 更多