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?

onclickとaddEventListener

Posted at

違い一覧

特徴 onclick addEventListener
設定方法 HTML属性、もしくはJSで element.onclick = function(){} element.addEventListener('click', function(){})
複数イベント登録 不可(上書きされる) 可能(同じ要素に何個でも追加できる)
イベントの種類 1種類のイベントにつき1つ 同じ種類でも複数登録可
削除 element.onclick = null element.removeEventListener('click', 関数名)
標準準拠 古い書き方もサポート 現代的・推奨
this の挙動 イベントが発生した要素を指す 同じく発生した要素を指す(ただしアロー関数を使うと this は外側のスコープになる)

onclickの上書きとは

ex.js
const btn = document.getElementById('myBtn');
btn.onclick = () => console.log('クリック1');
btn.onclick = () => console.log('クリック2');

btn.click(); // → "クリック2" しか出ない

addEventListenerの複数登録とは

Ex.js
const btn = document.getElementById('myBtn');
btn.addEventListener('click', () => console.log('クリック1'));
btn.addEventListener('click', () => console.log('クリック2'));

btn.click(); 
// → "クリック1"
// → "クリック2"
0
0
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
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?