7
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

【jQuery】追加した要素にon()のイベントが付与されない

Posted at

jQueryを書いていて、追加したボタンのクリックイベントが発火しない事象に遭遇。
調べてみると、on()の書き方に問題があった...教訓も兼ねて記事に残します。

本題#

例を挙げて説明します。
次のようなコードがあったとします。

example.html
<div class='parent'>
    <button id='a'>
</div>
example.js
$('button').on('click', function() {
    // イベント処理
});

ここにappendなど使ってhtmlにbutton要素を追加します。

example.html
<div class='parent'>
    <button id='a'>
    <button id='b'>
</div>

id が 'a' のボタンは正常にexample.jsのクリックイベントが実行されます。
しかし、id が 'b' のボタンはクリックイベントが実行されません。

これはon()で対象としている要素が追加されたとしても、追加された要素にはイベントが付与されないためです。
そのため、画面読み込み時から存在する要素に対してon()を適用させる必要があります。

対処法#

① $(document).on()を使う###

$(document).on()を使うことで追加要素にもイベントを付与できます。

$(document).on('イベント', '要素', '処理');

前述の例に適用すると下記になります。

example.js
$(document).on('click', 'button', function() {
    // イベント処理
});

② 親要素を指定する###

画面読み込み時から存在する親要素を指定し、その子要素に対してイベントを付与することで追加された要素でもイベントが発火します。

$('親要素').on('イベント', '子要素', '処理');

前述の例に適用すると下記になります。

example.js
$('div').on('click', 'button', function() {
    // イベント処理
});

参考になれば幸いです。

参考文献#

jQueryでclickイベントが効かない場合の対処法!
https://qumeru.com/magazine/401

7
3
0

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
7
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?