我正在创建一个可以在页面上创建任意数量的验证码的captcha
类。我有一个用于实例化新验证码对象的类c1
和c2
. 这是我的 JS:
$(function(){
var captcha = {
parentForm : '',
container : '',
captcha_input : '',
number1 : 0,
number2 : 0,
createCaptcha : function(form_ID){
var newHtml;
this.parentForm = $('#' + form_ID);
this.container = this.parentForm.find('.captchaContainer');
this.number1 = this.randomNumber(10);
this.number2 = this.randomNumber(10);
newHtml = 'What does ' + this.number1 + ' plus ' + this.number2 + ' equal? <b class="required goldenrod" title="Required Field">*</b><br/><br/><input type="text" name="captcha">';
this.container.html(newHtml);
},
isValid : function(){
console.log(this.container);
this.captcha_input = this.container.find('input[name="captcha"]');
if (this.number1 + this.number2 == this.captcha_input.val()) {
this.captcha_input.css('background-color', '')
return true;
} else{
this.captcha_input.css('background-color', '#FFCCCC')
alert(this.number1 + ' plus ' + this.number2 + ' does not equal ' + this.captcha_input.val() + '. Please try again.');
this.captcha_input.focus();
return false;
}
},
randomNumber : function(max){ return Math.floor(Math.random()*(max+1)); }
}
var c1 = captcha,
c2 = captcha;
c1.createCaptcha("form1");
c2.createCaptcha("form2");
$('#form1 input[type="submit"]').click(function() {
if(c1.isValid()){
alert('Captcha is valid!');
}else{
return false;
}
});
$('#form2 input[type="submit"]').click(function() {
if(c2.isValid()){
alert('Captcha is valid!');
}else{
return false;
}
});
});
还有我的 HTML:
<form id="form1">
<div class="captchaContainer"></div>
<input type="submit">
</form>
<form id="form2">
<div class="captchaContainer"></div>
<input type="submit">
</form>
当我单击form1
的提交按钮时,似乎isValid
正在运行该方法,c2
而不是c1
像我期望的那样。知道为什么会这样吗?
需要注意的几点:
- 如果我添加更多
captcha
实例和 HTML,则每个提交按钮都将在单击isValid
的最后一个实例上运行。captcha
- 这需要适用于 IE8+
这是实际代码的小提琴。
任何帮助将不胜感激。谢谢!