2016-07-14 4 views
0

DomNodeInsertedが推奨されていません。 MutationObserverの唯一の例は、更新されている要素、追加されていない要素を示しています。domのクラス作成時

動的に作成される特定のクラスの新しい要素をリッスンするにはどうすればよいですか?

+1

DOMノードを要素に追加すると、親権利の更新イベントがトリガされますか? ':)' –

答えて

-1

あなたはすぐにクラスが追加されたとして、あなたがイベントをトリガすることを求めていることがある:

$(document).on('click', function(){ 
$('#theid').addClass('classname').trigger('classChange'); 
}); 


$('#theid').on('classChange', function() { 
// do stuff 
}); 

何か他のものは説明してください場合:

+0

なぜjQueryを使うのですか? – aximus

+0

ああ、それはポイントですよね:) –

+0

@ ManinderSingh私はajaxリクエストを作成してから、データを編集するためのボタンを持つテーブルを作成しています。基本的に別のjsクラスを作成して、ボタンが作成されたらボタンの外観を操作できるようにしたかったのです。私は基本的にフックを作っていたので、jsファイルは追加設定なしでシステムのどの部分にもドロップすることができます。だから私はボタンの作成の外にボタンを操作することができるようにしたい – rob

0

あなたが正しいMutationObserverInitを渡すことによってこれを行うことができますMutationObserver。あなたはtruesubtreeを設定し、attributeFilter追加する必要があります。ここに

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

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

// configuration of the observer: 
var config = { attributes: true, childList: false, characterData: false, subtree: true, attributeFilter: ['class']}; 

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

var myElement = document.createElement('div'); 
myElement.innerHTML = 'foo'; 
target.appendChild(myElement); 

//triggers the mutation observer 
myElement.classList.add('bar'); 

JSFiddle:https://jsfiddle.net/7zwraaxz/3/

(DOMNODEのクラス名のように)classを(https://hacks.mozilla.org/2012/05/dom-mutationobserver-reacting-to-dom-changes-without-killing-browser-performance/に基づいて)次の例を考えてみましょう

関連する問題