<!DOCTYPE html> <html lang="zh-CN"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Title</title> </head> <body> <p class="code"></p> <button>生成驗證碼</button> <script> //驗證碼函數 function createCode(length) {//驗證碼長度 var code = ""; for (var i = 1; i <= length; i++) { code += (parseInt(Math.random() * 10)); } return code; } //輸出函數 function deal() { document.getElementsByClassName("code")[0].innerText = "生成的驗證碼:" + createCode(4); } //事件處理 document.getElementsByTagName("button")[0].onclick = deal; </script> </body> </html>