javascript - 如何使用 JavaScript 等待元素存在?

标签 javascript jquery ecmascript-6 promise es6-promise

我正在使用代理对象,在其中检测对象值更改,然后通过 AJAX 加载新内容,我使用 setInterval 函数等待,直到AJAX请求中传入的元素存在,然后执行一段代码。我这样做是因为我的情况需要这样做。我做了一个简短的例子:

var handler = {
    makeThings: 0,
    otherStuff: 0
};
var globalHandler = new Proxy(handler, {
    set: function(obj, prop, value) {
        obj[prop] = value
        if (prop == "makeThings") {
            var clearTimeSearchProxy = setInterval(function() {
                if ($("p").length) {
                    console.log("The element finally exist and we execute code");
                    clearTimeout(clearTimeSearchProxy);
                }
            }, 100);
        }
        return true;
    }
});

$(document).ready(function() {
    $("button").on("click", function() {
        globalHandler.makeThings = 1;
        //This element comes with ajax but I use a setTimeout for this example
        setTimeout(function() {
            $("#newContent").append("<p>Ajax element</p>");
        }, 2000);
    });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<body>
  <button>New content</button>
  <div id="newContent"></div>
</body>

现在我想知道如何以更干净、高效和优雅的方式改进代码。当通过 AJAX 传入的元素存在于 DOM 中时,我正在考虑使用 promises 而不是 setInterval 来执行代码。

我怎样才能让它发挥作用?对于这种情况,我应该使用其他 JavaScript 功能而不是 promises 吗?我坚持实现我所需要的 promise ,这是我迄今为止所尝试的。

var handler = {
    makeThings: 0,
    otherStuff: 0
};
var globalHandler = new Proxy(handler, {
    set: function(obj, prop, value) {
        obj[prop] = value
        if (prop == "makeThings") {
            var myFirstPromise = new Promise((resolve, reject) => {
                if ($("p").length) {
                    resolve("Exist");
                } else {
                    reject("It doesnt exist.");
                }
            });

            myFirstPromise.then((data) => {
                console.log("Done " + data);
            }).catch((reason) => {
                console.log("Handle rejected promise: " + reason);
            });
        }
        return true;
    }
});

$(document).ready(function() {
    $("button").on("click", function() {
        globalHandler.makeThings = 1;
        //This element comes with ajax but I use a setTimeout for this example
        setTimeout(function() {
            $("#newContent").append("<p>Ajax element</p>");
        }, 2000);
    });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<body>
  <button>New content</button>
  <div id="newContent"></div>
</body>

最佳答案

不要等待。而是订阅目标元素更改的通知。

用于监听 DOM 树中更改的 API 是 MutationObserver .

The MutationObserver interface provides the ability to watch for changes being made to the DOM tree. It is designed as a replacement for the older Mutation Events feature which was part of the DOM3 Events specification.

使用它来观察元素的变化,如下所示:

// You selected `$("p")` in your snippet, suggesting you're watching for the inclusion of 'any' `p` element.
// Therefore we'll watch the `body` element in this example
const targetNode = document.body;

// Options for the observer (which mutations to observe)
const config = {
    attributes: false,
    characterData: false,
    childList: true,
    subtree: true
};

// Callback function to execute when mutations are observed
const callback = function(mutationsList, observer) {
    for(let mutation of mutationsList) {

        if ( mutation.type === "childList" ) {
            continue;
        }

        const addedNodes = Array.from( mutation.addedNodes) ;

        if ( addedNodes && addedNodes.some( node => node.nodeName === "P" ) ) {
            observer.disconnect();

            console.log("The element finally exist and we execute code");
        }
    }
};

// Create an observer instance linked to the callback function
const observer = new MutationObserver(callback);

// Start observing the target node for configured mutations
observer.observe(targetNode, config);

关于javascript - 如何使用 JavaScript 等待元素存在?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57391677/

相关文章:

javascript - 在下面的 React ES6 示例中,如何可能引用没有 'this.state' 的对象属性?

javascript - 可以触发 HTTP 请求的 HTML 元素

javascript - 仅在 JavaScript 字符串中选择数字

javascript - 复制模式但更改文本和图像

javascript - 使用 ES6 模块的 TypeScript 的最佳方法是什么?

javascript - Object.fromEntries 仅在 iOS 上可用? ( react native - 不是网络)

javascript - 了解 Javascript .sort 参数

javascript - 如何在 ReactJS 中渲染 HTML 模板并绑定(bind)来自 JSON 响应的数据?

javascript - 如何创建动画图像的下载链接

javascript - 将 JSON .get 结果简单存储在数组中?