1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

動的に追加される要素に対してイベントを付与

Posted at

イベントデリゲーション(Event Delegation)

通常、静的な要素には直接イベントリスナーを設定できるが、動的に生成される要素には適用されない。
そこで、親要素にイベントを設定し、動的な要素にもイベントを適用する。

実装例

samle_html
<div id="hoge">
  <button class="foo">ボタン1</button>
  <button class="foo">ボタン2</button>
</div>
<button id="add">ボタン追加</button>
samle_js
// 個々の要素に直接イベントを付与(動的な要素には適用されない)
$('#hoge .foo').on('click', function(e) {
  alert('ボタンがクリックされました!');
});

// 親要素にイベントを設定(イベントデリゲーション:動的要素にも適用可能)
$('#hoge').on('click', '.foo', function(e) {
  alert('ボタンがクリックされました!');
});

// 動的にボタンを追加する
$('#add').on('click', function() {
  $('#hoge').append('<button class="foo">新しいボタン</button>');
});
1
0
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?