2
5

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 5 years have passed since last update.

jQueryで動的ボタンにアクションを追加する

Last updated at Posted at 2017-06-20

ボタンを押したら何かが起きてほしい。

 静的なボタンにアクション追加するときとjQueryで追加したボタンにアクションを追加するときで、書き方違ったので記録する。

静的なボタンの場合

index.html
<dl id="body">
  <button id="hoge">hoge</button>
  <button id="fuga">fuga</button>
  <button id="hoga">hoga</button>
</dl>
button_action.js
$(function () {
    $("#hoge").click(function(e) {
    $(this).text("Hello World!");
  });
});

すると
キャプチャ.PNG

キャプチャ2.PNG
となる。
やっていることは、'hoge'というidにclickイベントを追加しているだけ。
clickされると、function(e)が実施され、

動的なボタンの場合

なぜか静的なボタンのように記述してもうまくいかない。
実は、最近のjQueryではclickは推奨されておらずonを使用すべきということ。
onで書いてみる。(index.htmlに動的に要素追加する方法:jQueryで画面にボタンを付ける - Qiita

button_action.js
$(function () {
    $("#hoge").on("click",function(e) {
    $(this).text("Hello World!");
  });
});

上記の記述は、onを使用してhogeというidにclickイベントを追加する書き方。
簡単ですね。

でも、実はこれ動きません。
動的なボタンにアクションが追加されない理由は、非推奨なclickを使っているからではないようで、
結局、"hoge"というidはindex.html起動時に存在しないため、探しても見つからないというのが原因のようです。

ということで、以下のように変更

button_action.js
$(function () {
    $(document).on("click", "#hoge",function(e) {
    $(this).text("Hello World");
  });
});

ポイントは、onを呼び出す要素がdocumentになり、onの第二引数に"#hoge"が入っていること。
documentを指定すると、button_action.jsの呼び出し元がすべて対象になる。
そして、onの第二引数に要素を指定すると、 onを呼び出した範囲で特定の要素のみにイベントを追加する ということになる。
つまり、htmlファイル全体を走査し、その中でidがhogeの要素のみにイベントを追加する。という記述となる。

これで、動的なボタンにもイベントが追加出来ました。

2
5
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
2
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?