LoginSignup
23
16

More than 5 years have passed since last update.

jQueryで後から追加した要素にイベントを設定させる方法

Posted at

jQueryを使っていて、あれ?、なぜイベントを設定したのに動作しないんだ? と少し
ハマったことがあったので、アウトプットしたいと思います。

前提

jquery-3.4.0.min.jsを読み込んで動作確認をしています。

Example

単純に以下のように、ボタンを押すとp要素が追加されていく例を見ていきます。

example.html
<!DOCTYPE html>
<html lang="ja">
<head>
    <meta charset="utf-8">
    <title>jQueryの練習</title>
</head>
<body>
    <p>jQueryの練習</p>
    <button>Add!</button>

    <script src="https://code.jquery.com/jquery-3.4.0.min.js"></script>
    <script>
        $(function() {

            $('button').click(function() {
                // テキストが"add!!!"で"add"クラスを持つp要素をボタンの直前に追加する。
                var p = $('<p>').text('add!!!').addClass('add');
                $(this).before(p);
            });

            // 追加された"add"クラスを持つp要素をクリックすると削除される処理
            // 実はこの処理の書き方が問題あり!
            $('.add').click(function() {
                $(this).remove();
            });

        });
    </script>
</body>
</html>

実はこのように書くと、追加された"add"クラスを持つp要素にイベントが設定されず、
うまいこと消えてくれない。。。

onメソッドを使いましょう!

後から追加された要素にイベントを設定させたい場合は、onメソッドを使うことで解決できます!

example.html
<!DOCTYPE html>
<html lang="ja">
<head>
    <meta charset="utf-8">
    <title>jQueryの練習</title>
</head>
<body>
    <p>jQueryの練習</p>
    <button>Add!</button>

    <script src="https://code.jquery.com/jquery-3.4.0.min.js"></script>
    <script>
        $(function() {

            $('button').click(function() {
                // テキストが"add!!!"で"add"クラスを持つp要素をボタンの直前に追加する。
                var p = $('<p>').text('add!!!').addClass('add');
                $(this).before(p);
            });

            // このように書いてあげれば、うまく動作します!
            // jQueryオブジェクトの中は、$('body')ではなく$(document)としてもokです。
            $('body').on('click', '.add' , function() {
                $(this).remove();
            });

        });
    </script>
</body>
</html>

上記のように、

jQueryオブジェクト.on('イベントの種類', 'セレクタ' , function() {
});

とすれば、問題なく動作します。
かなり初歩的なことみたいです。

参考

ドットインストール
jQuery入門
#15 onメソッドを使ってみよう

23
16
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
23
16