1

さて、表示されるテキストを除いて基本的に同じオブジェクトがいくつかあります。それらがクリックされると、既存のイベント ハンドラーでアクションを実行します。

<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) を除いて、コードは、ブラウザの「要素の検査」で観察した場合とまったく同じです。イベント ハンドラーは、ページと共に読み込まれる要素に対して機能しますが、動的に作成されたオブジェクトに対しては何も起こりません。

動的に挿入されたオブジェクトの既存のイベント ハンドラーを登録できますか、それともまったく別の操作を行う必要がありますか?

4

2 に答える 2

3

delegate次のようにする必要があります。

$('#container').on('click','.myclass', function () {
  ('this').css("background-color","red");
  //Some other junk happens here, but the red background is easily observed
});

また

$(document).on('click','.myclass', function () {
  ('this').css("background-color","red");
  //Some other junk happens here, but the red background is easily observed
});
于 2013-06-05T21:33:17.553 に答える
2

イベントを委任する

$(staticContainer).on('click', '.myClass' function () {

staticContainerイベントがバインドされたときに DOM に存在する任意のコンテナーです。

Closest staticContainerあなたの場合はそうかもしれません'#container'

要素に近いほど良い

于 2013-06-05T21:34:14.757 に答える