<!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>