0
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?

More than 5 years have passed since last update.

[jQuery] onメソッドの使い方

0
Posted at

jQueryを使って動的な要素にイベントを付けるときによく使うメソッド。

jQueryは動的な言語なので、書いた構文がドキュメントに存在しないことになってしまう。
つまり、ある構文の下にその構文に対してイベントを与えたい構文を書いても、上にある構文は存在していないので影響を与えられない。

$("button").click(function(){
var p = $('

').text('ok!').addClass('ok');
$(this).before(p);
});

$(".ok").click(function(){
$(this).remove();
});

↑このような感じでok!の文字を消そうとしても、消すことができない

そのような際に、onメソッドを使えば、構文に対してイベントを与えられる。

$("button").click(function(){
var p = $('

').text('ok!').addClass('ok');
$(this).before(p);
});

$('body').on('click', '.ok', function() {
$(this).remove();
});

↑こうすれば、ok!の文字を消すことができる

0
0
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
0
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?