必须引入jQuery
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>random</title> </head> <body> <input type="text"><span></span> <input type="button" id="random"> <input type="button" id="submit" value="提交"> </body> </html> <script src="js/jquery-1.10.2.js"></script> <script> // 创建数组 var chars = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']; // 取出数组个数 var len = chars.length - 1; // 生成随机整数 var a = (Math.random() * len).toFixed(); var b = (Math.random() * len).toFixed(); var c = (Math.random() * len).toFixed(); var d = (Math.random() * len).toFixed(); // 取出数组中的值 var A = chars[a]; var B = chars[b]; var C = chars[c]; var D = chars[d]; var str = A + " " + B + " " + C + " " + D; $('#random').val(str); $('input[id=submit]').click(function () { // 取到文本里的值 var txt = $('input[type=text]').val(); var btn = $('input[id=random]').val(); var strs = ""; // 循环添加空格 for (var i = 0; i < txt.length; i++) { strs += txt[i] + ' '; } // 判断验证 if (strs.trim().toLowerCase() === btn.trim().toLowerCase()) { alert(true) } else { $('span').html('验证码错误') } }) </script>