LoginSignup
3
1

More than 3 years have passed since last update.

jQueryでclickイベントのDom取得

Posted at

はじめに

jQueryのクリックイベントで発火元のDOMを取得する方法をご紹介します。
コールバック関数が、無名関数function()を使う場合とアロー関数() => {}を使う場合で異なりますので、その点についてご紹介できればと思います。

環境

  • ES6
  • jQuery3.3.1

イベントの発火元は以下のボタンを想定しております。

<button type="button" class="add-item" data-index="1">追加</button>

無名関数を使う場合

$('.add-item').on('click', function() {
  const value = $(this).data('index');
  console.log(value);
});

// 1
$('.add-item').on('click', function (event) {
  const value = $(event.target).data('index');
  console.log(value);
});

// 1

アロー関数を使う場合

$('.add-item').on('click', (event) => {
  const value = $(event.target).data('index');
  console.log(value);
});

// 1

アロー関数ではthisの中身が違う物になります。
詳しくは以下のサイトが詳しく説明してくれていますので、参考にしてみてください。
【JavaScript】アロー関数式を学ぶついでにthisも復習する話

参考

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