A Pen by Hua-Ying Tsai on CodePen.
Created
February 12, 2023 05:24
-
-
Save enlineaweb/1997dc011ea92db719f6cffdf90cb0d5 to your computer and use it in GitHub Desktop.
Button Click Event Listener
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!-- 點擊按鈕的3種事件監聽範例 --> | |
<button onclick="clickButton1()">Button 1</button> | |
<button id="button2">Button 2</button> | |
<button id="button3">Button 3</button> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 方法1: 定義一個 function,然後再按鈕裡定義 onclick 等於這個 function 的名稱 | |
// 用戶在點擊按鈕時就會執行這個 function 裡的邏輯 | |
function clickButton1() { | |
alert("Button 1 is clicked.") | |
} | |
// 方法2: 使用 Javascript 的 document.getElementById 用 button id 拿到 button2 的個 html 元件(我們稱它為 DOM element)。 | |
// 然後用 button2.onclick 去定義這個要執行的 function | |
const button2 = document.getElementById("button2"); | |
button2.onclick = function() { | |
alert("Button 2 is clicked.") | |
} | |
// 方法3: 用 addEventListener 去實現事件監聽,其第一個參數 click 是事件名稱, addEventListent 支援各式各樣的事件。最推薦此方法。 | |
const button3 = document.getElementById("button3"); | |
button3.addEventListener('click', function() { | |
alert("Button 3 is clicked.") | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment