2016-04-12 3 views
1

要素がDOMに追加されたときにイベントがトリガーされるようにしたいと思います。これについて直感的に考えることができます:ノードがDOMに追加されたときに反応するjQueryイベント(またはハック)

//pick the generic selector of your choice. 
//The naive idea is to execute this handler when an element satisfying 
// this selector is added to the DOM. 
$('my-tag.my-class:my-pseudo-selector').ready(function() { 
    // do initialization for element 
}); 

これは機能しません。これはどちらでもありません。

$(document).on('ready', 'my-tag.my-selector:my-pseudo-selector', function() { 
    // do initialization for every element added to the dom, now and in the future 
}); 

.ready is only intended to work with document以降です。

エレメントを後でDOMに追加するときに、どのように動作させるか、またはハッキングをトリガーするにはどうすればよいですか?この追加は、次の3つの方法のいずれかで非同期javascriptによって実行されます。

  • Ajax .js responses。
  • ajaxレスポンスのJSハンドラ。
  • .html('<my-tag class="my-class" />')のようなコール、またはinsertBeforeinsertAfterappendToappend、などと呼ばれるコールがあります。

答えて

2

ここhttps://developer.mozilla.org/en-US/docs/Web/API/MutationObserver

は一例で試してみてください。

var whatToObserve = {childList: true, attributes: true, subtree: true, attributeOldValue: true, attributeFilter: ['class', 'style']}; 
var mutationObserver = new MutationObserver(function(mutationRecords) { 
    $.each(mutationRecords, function(index, mutationRecord) { 
    if (mutationRecord.type === 'childList') { 
     if (mutationRecord.addedNodes.length > 0) { 
     //DOM node added, do something 
     } 
     else if (mutationRecord.removedNodes.length > 0) { 
     //DOM node removed, do something 
     } 
    } 
    else if (mutationRecord.type === 'attributes') { 
     if (mutationRecord.attributeName === 'class') { 
     //class changed, do something 
     } 
    } 
    }); 
}); 
mutationObserver.observe(document.body, whatToObserve); 
+0

あなたは小さなフィドルをもたらすことはできますか? –

1

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

$(document).bind('DOMSubtreeModified', function() { 
 
    console.log('document change'); 
 
}); 
 

 
$('input[type=button]').on('click', function() { 
 
    $('body').append("<div>append element via button click</div>"); 
 
}); 
 

 
$('body').append("<div>append element</div>");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 

 
<input type='button' value='click' />

+0

あなたはあなたです!イベントはブラウザ間で行われますか? –

+0

待ち時間!おそらく私のハンドラの振る舞いはDOMの一部を更新し、無限ループを望んでいません。どのようなDOM変更が行われたかを知る方法はありますか? –

+0

私はそれがすべての主要なブラウザでサポートされていると思っています(ie7、ie8はわかりません) –

関連する問題