點選按鈕後JavaScript執行求和功能
假設我們的按鈕如下 -
<button type="button" onclick="addTheValue(10)">Sum </button> </body>
在按鈕點選事件中,我們用引數 10 呼叫函式 addTheValue(10)。在點選按鈕後,我們新增值 10,如下面程式碼所示 -
示例
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initialscale= 1.0"> <title>Document</title> <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> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/fontawesome/ 4.7.0/css/font-awesome.min.css"> </head> <body> <p> <h1> Adding 10 each time whenever you click the Sum Button......</h1> </p> <b id="firstValue">10</b> <button type="button" onclick="addTheValue(10)">Sum </button> <script> function addTheValue(secondValue) { var fValue = document.getElementById("firstValue"); firstValue.innerHTML = parseInt(fValue.innerHTML) + parseInt(secondValue); } </script> </body> </html>
要執行上述程式,請儲存檔名 “anyName.html(index.html)”,然後右鍵單擊該檔案。在 VS Code 編輯器中選擇選項 “使用 Live Server 開啟”。
將生成以下輸出 -
現在,我第一次點選 “求和” 按鈕。
將生成以下輸出 -
廣告