javascript:等到xpath存在超时?

时间:2014-08-21 05:49:11

标签: javascript

基本上,我想等待元素出现(例如动态加载的元素)。我想知道如何编辑它来支持xpath,不同的DOM文档(例如动态加载的iframe),还设置一个超时值,以便在X秒后,如果找不到该元素,它将退出,抛出错误我可以处理。

waitUntilExists(xpath,document,5,function(){
 // Element exists, if after 5 seconds and it doesn't exist handle it here.
})

要修改的原始代码:

(function(){
    var _waitUntilExists = {
        pending_functions : [],
        loop_and_call : function()
        {
            if(!_waitUntilExists.pending_functions.length){return}
            for(var i=0;i<_waitUntilExists.pending_functions.length;i++)
            {   
                var obj = _waitUntilExists.pending_functions[i];
                var resolution = document.getElementById(obj.id);
                if(obj.id == document){
                    resolution = document.body;
                }
                if(resolution){
                    var _f = obj.f;
                    _waitUntilExists.pending_functions.splice(i, 1)
                    if(obj.c == "itself"){obj.c = resolution}
                    _f.call(obj.c)                          
                    i--                 
                }
            }
        },
        global_interval : setInterval(function(){_waitUntilExists.loop_and_call()},5)
    }
    if(document.addEventListener){
        document.addEventListener("DOMNodeInserted", _waitUntilExists.loop_and_call, false);
        clearInterval(_waitUntilExists.global_interval);
    }
    window.waitUntilExists = function(id,the_function,context){
        context = context || window
        if(typeof id == "function"){context = the_function;the_function = id;id=document}
        _waitUntilExists.pending_functions.push({f:the_function,id:id,c:context})
    }
    waitUntilExists.stop = function(id,f){
        for(var i=0;i<_waitUntilExists.pending_functions.length;i++){
            if(_waitUntilExists.pending_functions[i].id==id && (typeof f == "undefined" || _waitUntilExists.pending_functions[i].f == f))
            {
                _waitUntilExists.pending_functions.splice(i, 1)
            }
        }
    }
    waitUntilExists.stopAll = function(){
        _waitUntilExists.pending_functions = []
    }
})()

0 个答案:

没有答案