Help us understand the problem. What is going on with this article?

jQueryでclickイベントのDom取得

はじめに

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も復習する話

参考

Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした