gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 14:15:57 26 4
gpt4 key购买 nike

我正在使用代理对象,在其中检测对象值更改,然后通过 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com