Why not login to Qiita and try out its useful features?

We'll deliver articles that match you.

You can read useful information later.

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?

event.targetプロパティを使用したプログラム例

Last updated at Posted at 2024-11-16

1. 概要

event.targetは JavaScript でイベントが発生した要素を指します.

ここではチェックボックスの切り替えを検出して,その結果をコンソールに出力する簡単な例を紹介します.

(初心者の勉強記録です.)

2. 実装例

2.1. チェックボックスの設置

以下の HTML コードによりチェックボックスを作成します.

<!-- HTML -->
<div>
    <input type="checkbox" id="sample-Btn">チェックボックス
</div>

2.2. ボタン要素の取得

sample-Btn というIDを持つ要素を取得し,変数 checkBtn へ格納する.

//script
const checkBtn = document.getElementById('sample-Btn');

2.3. イベントリスナー設定

チェックボックスの状態が変わったときに typeChange 関数を呼び出す.

//script
checkBtn.addEventListener('change', typeChange);

2.4. typeChange関数

event.targetを使用して,チェックボックスの状態を Console へ出力する関数の実装.

//script
function typeChange(event) {
    console.log('チェックボックスの状態:', event.target.checked);

    // チェックされた場合
    if (event.target.checked) {
        console.log('チェックされました');
    }else{
        console.log('チェックが外されました');
    }
}

2.5. 結果

3. まとめ

event.target は「そのイベント(今回はチェックする)が発生した要素」を指します.

CodePenなどで上記のコードを貼り付けてみてください.
Consoleに,エラーに応じたメッセージが表示されていると思います.

最後まで読んでいただきありがとうございまいた.

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

Comments

dgcdsbsd2
@dgcdsbsd2

記載のコードだと、event.target.checkedcheckBtn.checkedにしても結果が同じなのでevent.targetの説明にはなっていないのではないでしょうか。

event.targetのサンプルなら、イベントデリゲーションを使う方法が分かりやすいと思います。

<style>
td {
  border: 1px black solid;
  width: 20px;
  height: 20px;
  padding: 0;
}
</style>

<table></table>

<script>
const tableElem = document.querySelector('table');
tableElem.innerHTML = `<tr>${'<td></td>'.repeat(20)}</tr>`.repeat(20);

tableElem.addEventListener('pointerover', event => {
  if (event.target.nodeName === 'TD') {
    event.target.style.backgroundColor = 'red';
  }
});
</script>

0

Let's comment your feelings that are more than good

Qiita Advent Calendar is held!

Qiita Advent Calendar is an article posting event where you post articles by filling a calendar 🎅

Some calendars come with gifts and some gifts are drawn from all calendars 👀

Please tie the article to your calendar and let's enjoy Christmas together!

Being held Article posting campaign

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?

Login to continue?

Login or Sign up with social account

Login or Sign up with your email address