2015-11-12 40 views
1

我正在使用第三方插件。 而我需要改變一些CSS。.on沒有點擊的授權事件

我不能依靠點擊或其他鼠標或鍵盤事件。

我需要當屏幕上存在「x」元素時,它會收到一些類。

$(document).on('ready load', '.form-row', function() { 
    $(this).addClass('radio'); 
}); 

我知道有人會複製關於加載事件的jquery文檔。

但是我需要當某個元素插入到DOM中時它會接收這個類。

我已經在舊版本的jQuery這樣做,我不明白爲什麼現在它不會工作

+2

我不認爲這有效。常規元素上沒有加載事件。你可以聽突變事件 –

+1

你不能委託'ready'或'load'事件,因爲它們只觸發一次,而不是在子元素上。如果在需要的元素被添加到DOM時發生事件,如果您可以添加事件掛鉤,請檢查插件。 –

+1

根據您的兼容性要求,您可以使用[Mutation Observers](https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver)。 – Phylogenesis

回答

0

使用MutationObserver你可以聽DOM變化,特定HTML節點,或整個DOM .. 。

  • 注:您應檢查MutationObserver的瀏覽器的兼容性,以確保它符合您的需求。

這裏是一個示例代碼,看看它是如何工作的:

// select the target node 
var target = document.querySelector('#some-id'); 

// create an observer instance 
var observer = new MutationObserver(function(mutations) { 
    mutations.forEach(function(mutation) { 
    console.log(mutation.type); 
    });  
}); 

// configuration of the observer: 
var config = { attributes: true, childList: true, characterData: true }; 

// pass in the target node, as well as the observer options 
observer.observe(target, config); 

// later, you can stop observing 
observer.disconnect(); 
+0

如果您打算使用此功能,請務必查看瀏覽器兼容性,因爲它僅限於現代瀏覽器。 – epascarello

+0

@epascarello你是對的。添加了一個註釋... –

0

嘗試DOMNodeInserted,你可以針對一個特定的元素,其中插入將於(.container): -

$(document).on('DOMNodeInserted', '.container', function() { 
 
    $('.form-row').addClass('radio'); 
 
}); 
 

 

 
$('<div></div>', { 'class':'form-row' }).appendTo('.container');
.container{ 
 
    background-color:blue; 
 
    padding:20px; 
 
} 
 

 
.radio{ 
 
    height:50px; 
 
    background-color:red; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div class="container"></div>