2015-03-02 42 views
0

我想檢查DOM(使用Internet Explorer)中是否存在jQuery對象。我想這樣的代碼:如何檢查DOM中是否存在jQuery對象?

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存在),我仍然得到這個的console.log每250毫秒。如何檢查元素是否存在於DOM中?我收到變量editor作爲參數。

請注意,編輯也可能在之內。

+4

這聽起來像是矯枉過正。你爲什麼需要這個?我相信這是一種更好的方式,無需每秒創建4次DOM請求。 – 2015-03-02 13:43:40

+0

@RoryMcCrossan我試圖使用'MutationObserver',但我無法使它在Internet Explorer中工作。我們對Chrome,Firefox和Safari具有相同的功能,它可以與'MutationObserver'一起使用。但由於它在Internet Explorer中不起作用,因此我將此函數設置爲每250毫秒運行一次。 – Uri 2015-03-02 13:49:12

回答

0

我發現一個解決方案,它不是理想的,但它的工作原理。我給每一個編輯的唯一數據屬性:

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

順便說一句,我改變了timout至100毫秒,因爲它與250

太慢
+0

順便說一下,如果編輯器位於iframe中,此解決方案不起作用。如果它在一個iframe中,我們必須在DOM中遞歸地搜索它。 – Uri 2015-03-02 15:02:39