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

如何使用JavaScript等待元素存在?,javascript,jquery,ecmascript-6,promise,es6-promise,Javascript,Jquery,Ecmascript 6,Promise,Es6 Promise,我使用的是代理对象,我检测到对象值的变化,然后通过AJAX加载新内容,我使用setInterval函数等待AJAX请求中的元素存在,然后执行一段代码。我这样做是因为我的案子需要它。我做了一个简短的例子: var处理程序={ makeThings:0, 其他资料:0 }; var globalHandler=新代理(处理程序{ 设置:功能(对象、属性、值){ obj[prop]=值 if(prop==“makeThings”){ var clearTimeSearchProxy=setInter

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

var处理程序={
makeThings:0,
其他资料:0
};
var globalHandler=新代理(处理程序{
设置:功能(对象、属性、值){
obj[prop]=值
if(prop==“makeThings”){
var clearTimeSearchProxy=setInterval(函数(){
如果($(“p”).长度){
log(“元素最终存在,我们执行代码”);
clearTimeout(clearTimeSearchProxy);
}
}, 100);
}
返回true;
}
});
$(文档).ready(函数(){
$(“按钮”)。在(“单击”,函数(){
globalHandler.makeThings=1;
//此元素随ajax提供,但我在本例中使用了setTimeout
setTimeout(函数(){
$(“#newContent”).append(“Ajax元素”

”; }, 2000); }); });

新内容
可以大大简化您的工作。一个非常基本的实现,仅使用主题和订阅:

const{
主题
}=rxjs;
const sub=新主题();
sub.subscribe(e=>{
log(`received data${e}`);
//做你的事
});
//模拟异步的东西
设置超时(()=>{
下一步(“foo”);
}, 1000);
可以大大简化您的工作。一个非常基本的实现,仅使用主题和订阅:

const{
主题
}=rxjs;
const sub=新主题();
sub.subscribe(e=>{
log(`received data${e}`);
//做你的事
});
//模拟异步的东西
设置超时(()=>{
下一步(“foo”);
}, 1000);
不要等待。而是订阅目标元素更改的通知

用于侦听DOM树中的更改的API是

MutationObserver接口提供监视DOM树更改的功能。它被设计为DOM3事件规范中较早的突变事件特性的替代品

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

// 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);
不要等待。而是订阅目标元素更改的通知

用于侦听DOM树中的更改的API是

MutationObserver接口提供监视DOM树更改的功能。它被设计为DOM3事件规范中较早的突变事件特性的替代品

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

// 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);
我终于用
界面
轻松地完成了,而不是用
承诺

var处理程序={
makeThings:0,
其他资料:0
};
var globalHandler=新代理(处理程序{
设置:功能(对象、属性、值){
obj[prop]=值
if(prop==“makeThings”){
var观察者=新的突变观察者(功能(突变){
如果($(“p”).长度){
log(“存在,让我们做点什么”);
observer.disconnect();
}
});
//开始观察
观察者,观察者(文件主体{
儿童名单:是的,
子树:真
});
}
返回true;
}
});
$(文档).ready(函数(){
$(“按钮”)。在(“单击”,函数(){
$(“p”).remove();
globalHandler.makeThings=1;
//此元素随ajax提供,但我在本例中使用了setTimeout
setTimeout(函数(){
$(“#newContent”).append(“Ajax元素”

”; }, 2000); }); });

新内容
我终于用
界面
轻松实现了,而不是用
承诺

var处理程序={
makeThings:0,
其他资料:0
};
var globalHandler=新代理(处理程序{
设置:功能(对象、属性、值){
obj[prop]=值
if(prop==“makeThings”){
var观察者=新的突变观察者(功能(突变){
如果($(“p”).长度){
log(“存在,让我们做点什么”);
observer.disconnect();
}
});
//开始观察
观察者,观察者(文件主体{
儿童名单:是的,
子树:真
});
}
返回true;
}
});
$(文档).ready(函数(){
$(“按钮”)。在(“单击”,函数(){
$(“p”).remove();
globalHandler.makeThings=1;
//此元素随ajax提供,但我在本例中使用了setTimeout
setTimeout(函数(){
$(“#newContent”).append(“Ajax元素”

”; }, 2000); }); });

新内容

这是否回答了您的问题?这回答了你的问题吗?是否有必要在配置中将“childList”设置为true,然后在观察者回调中跳过该突变类型?如果您确实确信
config
严格设置为观察子添加/删除,则不应检查突变类型。是否有必要在配置中将“childList”设置为true,然后跳过观察者回调中的突变类型?如果您确实确信
config
是为观察子添加/删除而严格设置的,那么您不应该检查突变类型。