LoginSignup
6
6

More than 3 years have passed since last update.

JavaScriptのボタンをクリックした際のイベント処理

Posted at
目次
記述の仕方(例)
inputについて
thisを関数の引数にすると面白いことができそう
inputを使わず、buttonを使う場合

記述の仕方(例)

  • HTML内で完結させる場合
html
<input type="button" value="ボタン" onclick="console.log(`Hello`)">

実行結果:Hello

  • 外部ファイルに関数を用意する場合
html
<input type="button" value="ボタン" onclick="func()">
js
const func = () => {
    console.log("Hello");
}

実行結果:Hello

  • 関数を複数実行もできる
html
<input type="button" value="ボタン" onclick="func();func2">
js
const func = () => {
    console.log("Hello");
}
const func2 = () => {
    console.log("World");
}

実行結果:Hello World

inputについて

<FORM></FORM>を構成する部品タグ。
typeでボタンやチェックボックス等の形を指定する。
valueでボタン上に表示するテキストを指定。
onclickではクリックされた際のイベント処理について記述する。

thisを関数の引数に指定すると面白いことができそう

html
<input type="button" value="ボタン" onclick="func(this)">
js
let func = (button) => {
    console.log(button.value);
}

実行結果:ボタン
thisは状況によってその中身が変化する変数。
宣言する必要はなく単体で利用できる。
今回はbuttonの属性valueを指定しました。

  • これによりボタンの上に表示されている文字をクリック後に変更することができる
html
<input type="button" value="ボタン" onclick="func(this)">
js
let func = (button) => {
    console.log(button.value = "OK!");
}

実行結果:OK!

inputを使わず、buttonを使う場合

html
<button id="btn">ボタン</button>
js
const x = document.getElementById(`btn`);

x.addEventListener(`click`, func = () => {
    console.log("OK!");
});

実行結果:OK!

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