LoginSignup
0
1

More than 1 year has passed since last update.

【JavaScript】イベント・イベントハンドラ② 「開始タグの中で関連付ける方法」

Last updated at Posted at 2021-11-15

1. はじめに

本記事では、【JavaScript】イベント・イベントハンドラの「開始タグの中で関連付ける方法」について記載する。

2. 開始タグの中で関連付け

構文

index.js
<要素名 on+イベント名 = 'イベントハンドラ'></要素名>

index.js
<input type="button" value="取得" onclick="show()" />

上記例の意味としては、

取得と書かれたボタンをクリックされるとshowメソッドを呼ぶ

という意味となる。

3. 例題

内容

ボタンをクリックすると、'イベント発生'と出力されるプログラムの作成

実践前のチュートリアル

実践に入る前に、完成形を先に表示しておく。
ezgif.com-gif-maker.gif


マークアップ

ブラウザに置換前の文字をブラウザへ表示しないといけないので、HTMLの作成から取り掛かる。

index.html
index.html
<!DOCTYPE html>
<html lang="ja">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <input type="button" value="クリック" onclick="clicked()" />
    <script src="js/index.js"></script>
  </body>
</html>


マークアップしブラウザで表示すると以下のようになる。
スクリーンショット 2021-11-15 11.37.36.png


JavaScriptの記述

次にJavaScriptを仕上げていく。

index.js
function clicked() {
  console.log('イベント発生');
}

今回はボタンをクリックしてコンソールに出力するだけの簡易的なものなので、詳細説明は省略する。


ブラウザでの検証

実際にブラウザにて挙動を確認していく。
ezgif.com-gif-maker.gif

検証の結果、

クリックボタンを押すと、コンソールへ'イベント発生'の文字列を出力することが出来た

4. おわりに

次項:【JavaScript】イベント・イベントハンドラ③ 「プロパティで関連付けする方法」に続く。

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