我正在尝试为项目创建自定义CAPTCHA,我想知道如何检查输入是否等于变量。
window.onload = function makeid() {
var text = "";
var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
var place = document.getElementById("random");
for( var i=0; i < 5; i++ ) {
text += possible.charAt(Math.floor(Math.random() * possible.length));
};
console.log(text);
place.innerHTML = text;
};
};
BTW我是javascript的新手。
随机字符串生成器部分不是我的。
答案 0 :(得分:1)
你在一个范围内有一个验证码,剩下要做的就是放置一个输入框,检索它的内容并将它们与验证码进行比较。(我用阿里的代码作为起点)
window.onload = function makeid() {
var text = "";
var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
var place = document.getElementById("random");
for (var i = 1; i <= 5; i++) {
text += possible.charAt(Math.floor(Math.random() * possible.length));
};
console.log(text);
place.innerHTML = text;
};
//This code waits for the user to press the enter key in order to trigger the function that compares the strings
inputbox = document.getElementById("userinput"); inputbox.addEventListener("keydown", function(e) {
if (e.keyCode === 13) { //checks whether the pressed key is "Enter"
validate(e);
}
});
//And this actually performs the comparison and shows a response
function validate(e) {
var captchatext = document.getElementById("random").innerHTML;
var usertext = document.getElementById("userinput").value;
if (captchatext == usertext) {
alert("Correct captcha");
} else {
alert("Incorrect captcha");
}
}
&#13;
<span id = "random" > < /span>
<input id = "userinput" type = "text" >
&#13;
答案 1 :(得分:0)
您需要修复一些语法问题:
window.onload = function makeid() {
var text = "";
var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
var place = document.getElementById("random");
for( var i=1; i <= 5; i++ ) {
text += possible.charAt(Math.floor(Math.random() * possible.length));
};
console.log(text);
place.innerHTML = text;
};
<span id="random"></span>
如果您想增加生成的字符串的长度,只需将此条件i <= 5
替换为另一个,例如:i <= 15
- &gt; 15个符号