さて、表示されるテキストを除いて基本的に同じオブジェクトがいくつかあります。それらがクリックされると、既存のイベント ハンドラーでアクションを実行します。
<div id="container">
<div class="myclass">...<p>foo</p>...</div>
<div class="myclass">...<p>bar</p>...</div>
<div class="myclass">...<p>foo</p>...</div>
...etc etc
<div>
<div id="button" class="button">button-to-do-something</div>
$('.myclass').on('click', function () {
('this').css("background-color","red");
//Some other junk happens here, but the red background is easily observed
});
$('#button').on('click', function() {
$('#container').append('<div class="myclass">...<p>bar</p>...</div>');
});
コンテナー div 内に myclass div の別のインスタンスを挿入するボタンを設定しましたが、動的に作成されたオブジェクトをクリックしても何もしません。内部テキスト (この例では foo または bar) を除いて、コードは、ブラウザの「要素の検査」で観察した場合とまったく同じです。イベント ハンドラーは、ページと共に読み込まれる要素に対して機能しますが、動的に作成されたオブジェクトに対しては何も起こりません。
動的に挿入されたオブジェクトの既存のイベント ハンドラーを登録できますか、それともまったく別の操作を行う必要がありますか?