简体   繁体   English

如何检查DOM中是否存在jQuery对象?

[英]How do I check if a jQuery object exists in the DOM?

I want to check if a jQuery object exists in the DOM (with Internet Explorer). 我想检查DOM中是否存在jQuery对象(使用Internet Explorer)。 I tried this code: 我试过这段代码:

observeEditor = function(editor) {
    function update_position() {
        console.log("update_position");
        var $editor = jQuery(editor);
        if (jQuery(document).find($editor).length > 0) {
            // call our function
            setTimeout(update_position, 250);
        }
    }
    setTimeout(update_position, 250);
};

But the problem is that even after I close the editor (it doesn't exist in the DOM), I still get this console.log every 250 ms. 但问题是,即使在我关闭编辑器(它在DOM中不存在)之后,我仍然每250毫秒获得一次这个console.log。 How do I check if the element exists in the DOM? 如何检查DOM中是否存在元素? I receive the variable editor as a parameter. 我收到变量editor作为参数。

Please notice, the editor may also be inside an <iframe> . 请注意,编辑器也可能在<iframe>

I found a solution, it's not ideal but it works. 我找到了一个解决方案,它并不理想但它有效。 I gave every editor a unique data attribute: 我给每个编辑器一个独特的数据属性:

if (($editor.length === 1) && (typeof($editor.attr('data-editor-id')) === 'undefined')) {
    $editor.attr('data-editor-id', Math.floor((Math.random() * 900000000000000) + 100000000000000));
}

And then I changed the function: 然后我改变了功能:

observeEditor = function(editor) {
    var $editor = jQuery(editor);
    var editor_id = undefined;
    if (($editor.length === 1) && (!(typeof($editor.attr('data-editor-id')) === 'undefined'))) {
        editor_id = $editor.attr('data-editor-id');
    }
    function update_position() {
        console.log("update_position");
        if (jQuery(document).find('[data-editor-id="' + editor_id + '"]').length > 0) {
            // call our function
            setTimeout(update_position, 100);
        }
    }
    setTimeout(update_position, 100);
};

By the way, I changed the timout to 100 ms because it's too slow with 250. 顺便说一句,我将时间改为100毫秒,因为它太慢了250。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM