使用 onclick() 呼叫函式 – JavaScript?
假設我們有以下按鈕 −
<button onclick="displayingMessageOnButtonClick()">Press Me</button>
我們需要在單擊上述按鈕時呼叫一個函式。
示例
以下是程式碼 −
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css"> <script src="https://code.jquery.com/jquery-1.12.4.js"></script> <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script> <body> <p id="showTheTextMessage"></p> <button onclick="displayingMessageOnButtonClick()">Press Me</button> </body> <script> function displayingMessageOnButtonClick() { const showMessage = document.getElementById('showTheTextMessage'); showMessage.innerHTML = 'Welcome to Javascript Program...'; showMessage.style.display = 'block'; } </script> </html>
要執行上面的程式,請將檔案命名為 anyName.html(index.html)。右鍵單擊該檔案,然後在 VS Code 編輯器中選擇選項“使用即時伺服器開啟” −
輸出
輸出如下 −
現在,單擊按鈕。以下是輸出 −
廣告