Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/411.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何检查DOM中是否存在jQuery对象?_Javascript_Jquery_Dom - Fatal编程技术网

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

Javascript 如何检查DOM中是否存在jQuery对象?,javascript,jquery,dom,Javascript,Jquery,Dom,我想检查DOM中是否存在jQuery对象(使用Internet Explorer)。我尝试了以下代码: observeEditor = function(editor) { function update_position() { console.log("update_position"); var $editor = jQuery(editor); if (jQuery(document).find($editor).length &g

我想检查DOM中是否存在jQuery对象(使用Internet Explorer)。我尝试了以下代码:

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);
};
但问题是,即使在关闭编辑器(DOM中不存在该编辑器)后,我仍然每隔250毫秒获得一次console.log。如何检查DOM中是否存在该元素?我接收变量
editor
作为参数


请注意,编辑器可能也在一个
中。我找到了一个解决方案,虽然不理想,但很有效。我给每个编辑器一个独特的数据属性:

if (($editor.length === 1) && (typeof($editor.attr('data-editor-id')) === 'undefined')) {
    $editor.attr('data-editor-id', Math.floor((Math.random() * 900000000000000) + 100000000000000));
}
然后我改变了功能:

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);
};

顺便说一句,我把计时改为100毫秒,因为250太慢了。

这听起来有点过头了。你为什么需要这个?我确信有一种更好的方法可以做到这一点,而不需要每秒发出4次DOM请求。@Rorymcrossan我曾尝试使用
MutationObserver
,但我无法在Internet Explorer中使用它。我们对Chrome、Firefox和Safari都有相同的功能,它可以与
MutationObserver
一起使用。但是,由于它在Internet Explorer中不起作用,我将此函数设置为每250毫秒运行一次。顺便说一下,如果编辑器位于iframe中,此解决方案将不起作用。如果它在iframe中,我们必须在DOM中递归地搜索它。