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?

【jQuery】動的に追加される要素にイベントを設定する

Posted at

動的に追加される要素にイベントを設定する方法と、
最初からHTMLで存在してる要素にイベントを設定する方法は少し違うので、
メモしておく。

まずは最初から存在している要素の場合。
$() は、ページが読み込まれたときに存在している要素に対してだけ動作する。

    $('#id-name button').on('click', function(event) {
	event.preventDefault();
        alert("click");
    });
    //或いは
    $('#id-name button').click(function() {
    alert("click");
});

後から追加される要素のイベント設定する場合、on()の中にその要素を指定する必要がある。

$(document).on('click', '#id-name button', function(event) {
    event.preventDefault();
    alert("click");
});
//或いは
$('#id-name').on('click', 'button', function(event) {
    event.preventDefault();
    alert("click");
});
/*id-nameという最初から存在している要素の配下に
現れてくるbuttonにイベントを設定する*/
0
0
2

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?