2016-12-19 1 views
2

私が使用するウェブサイトには、ユーザーフォームが組み込まれています。ユーザーフォームには、複数のドロップダウンリストが含まれています。実行時に( 'DOMContentLoaded'で)、ドロップダウンリストのいずれもデータを含んでいません。 DDLを開くと、Javascriptを実行してリストをページにロードすると仮定します。On 'ElementHasChildren'イベント

要素:

<ul class='hidden' data-bind='template: { name: 'childTreeTemplate', foreach: Kids }' style='display:block;'> 
    <li class='treeItem'>...</li> 
    <li class='treeItem'>...</li> 
    <li class='treeItem'>...</li> 
</ul> 

私はこれを検出するイベントを設定することができます。

<ul class='hidden' data-bind='template: { name: 'childTreeTemplate', foreach: Kids }' style='display:block;'></ul> 

'開口部' は3つの要素のリストがなった後?私はすでに試してみました

もの:

document.getElementsByTagName('ul')[1].addEventListener('DOMContentLoaded', function() { 
    alert('Content Loaded') 
}); 

document.getElementsByTagName('ul')[1].addEventListener('onchange', function() { 
    alert('Changed') 
}); 

document.getElementsByTagName('ul')[1].addEventListener('onload', function() { 
    alert('Loaded') 
}); 

要素がロードされるとき、これらのイベントのいずれもが引き金ません(私はおそらく、その使用を誤解)...

+0

私はuserformのマークアップを変更できないと思いますか?このページではライブラリKnockoutを使用しているので、最も信頼性の高いオプションは、** '** ko.applyBindings(...)'呼び出し後にコードが実行されるようにすることです。 –

+0

マークアップを変更する可能性がある場合は、見てください:http://stackoverflow.com/questions/11893291/how-to-get-event-when-knockout-binding-is-done –

+0

悲しいことに変更することはできませんマークアップは、サイトをロードする前にHTMLを変更する簡単な方法がない限りですか?以下の変異オブザーバの解決策は、私のニーズにもかかわらず動作します。私は今までノックアウトを聞いたことがない、そしてそれはなぜ主要なオブジェクトが "SEOko"であるのかを説明するだろう – Sancarn

答えて

2

あなたはMutationObserverを使用することができます。

MutationObserverは、 DOMの変更に対応する方法を開発者に提供します。 DOM3イベント仕様の で定義されている突然変異イベントの代わりに設計されています。

var target = document.getElementById('parent'); 
 

 
// create an observer instance 
 
var observer = new MutationObserver(function(mutations) { 
 
    mutations.forEach(function(mutation) { 
 
    if (mutation.type==='childList') { 
 
    \t alert('added!'); 
 
     return false; 
 
    } 
 
    });  
 
}); 
 
    
 
// 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); 
 

 
document.getElementById('parent').appendChild(document.createElement('li'));
<ul id="parent" style='display:block;'> 
 

 
</ul>

デモ:https://jsfiddle.net/q5nytv0L/

私は DOMNodeInsertedを使用していた過去に

が、それは非推奨です:

document.getElementById('parent').addEventListener('DOMNodeInserted', function (event) {  
 
    if(event.target.parentNode.id == 'parent') { 
 
     alert('added!');   
 
    }; 
 
    
 
}, false); 
 

 

 
document.getElementById('parent').appendChild(document.createElement('li'));
<ul id="parent" style='display:block;'> 
 

 
</ul>

関連する問題