MutationObserver 的属性更改仅在代码在循环内时发现

问题描述 投票:0回答:0

我在使用 js 和 MutationObserver 检测 html 元素的属性变化时遇到了一些问题。这是代码:

document.addEventListener("DOMContentLoaded", function() {

  const checkForLoading = setInterval(function () {

    let loading = document.getElementById("sequence");

    if (loading) {
        console.log("loading detected");

        const loadingObserver = new MutationObserver(function (mutations) {
          console.log("mutation detected");
          if (loading.getAttribute('data-dash-is-loading') === 'true') {
            console.log("loading");
            // loading.style.visibility = 'hidden';
          } else {
            console.log("not loading");
            // loading.style.visibility = 'visible';
          }
        });

        const observerOptions = {
          attributes: true,
        }

        loadingObserver.observe(loading, observerOptions);
        clearInterval(checkForLoading);
    }
  }, 100);
});

因为该元素无法立即使用,所以我设置了 checkForLoading 循环。属性 'data-dash-is-loading' 仅在元素加载时设置,否则不可用。只有在检测到序列元素并且未调用 clearInterval(checkForLoading) 后循环继续运行时,此代码才有效。但是我想避免不断运行这个循环。非常感谢解决此问题的任何帮助。

javascript html dom mutation-observers
© www.soinside.com 2019 - 2024. All rights reserved.