[英]Javascript Scope using JQuery
I am having trouble understanding why this is occurring. 我无法理解为什么会这样。 Here is a simplified version of my code:
这是我的代码的简化版本:
$( document ).ready(function() {
var mFormHelper = new FormHelper("form_add_ftransaction");
var mThing = $("#mThing");
form_add_ftransaction.submit(function(event){
//var mFormHelper = new FormHelper("form_add_ftransaction"); <-- unless i uncomment this it doesn't seem to work
var mloader = new Loader();
mloader.setLoading(mThing);//<----- mThing is available in scope...
mFormHelper.clearForm(); //<-------doesn't work unless mFormHelper is redeclared. Why not?
});
});
Why is it that the variable 'mThing' is accessible inside the jQuery .submit(function(){}) but 'mFormHelper' is not? 为什么变量'mThing'可在jQuery .submit(function(){})内访问而不能访问'mFormHelper'?
The error I get if i don't redeclare the mFormHelper is "Uncaught TypeError: Cannot read property 'find' of undefined" 如果我不重新声明mFormHelper,我将得到的错误是“未捕获的TypeError:无法读取未定义的属性'find'”
The FormHelper class is: FormHelper类是:
function FormHelper(formId){
context = this; //<--------------------------THIS WAS THE PROBLEM
this.form = $("#"+formId);
this.validate = function(){
var valid = true;
var requiredFields = context.form.find(".required");
requiredFields.each(function(){
$(this).removeClass("form_highlight");
var field = $(this);
if(field.attr("type") !=""){
field.type = field.attr("type");
}
//alert(field.attr("data-type"));
if(field.attr("data-type") == "radiogroup"){
if(field.find("input:checked").get() ==""){
field.addClass("form_highlight");
valid = false;
return true;
}
}
if((field.val() == "" || field.val() == null) && field.attr("data-type") != "radiogroup"){
field.addClass("form_highlight");
valid = false;
}
});
return valid;
};
/**
* Method markRequiredFields
*
* Adds an asterisk in front of label for all required fields in the form. required fields are noted with the '.required' class.
*/
this.markRequiredFields = function(){
var requiredFields = context.form.find(".required");
requiredFields.each(function(){
field = $(this);
var label = $("label[for='"+field.attr('id')+"'");
var str = label.html();
if(str != undefined){
label.html("*"+str.replace("*", ""));
}
});
}
this.clearForm = function (){
this.form.find(':input').not(':button, :submit, :reset, :hidden, :checkbox, :radio').val('');
this.form.find(':checkbox, :radio').prop('checked', false);
this.form.removeAttr("class", "form_highlight");
}
} }
So I solved the issue after your helpful comments instructed me that it should be in scope. 因此,在您的有用评论指示我应该在范围内之后,我解决了该问题。
In my FormHelperClass the problem was: 在我的FormHelperClass中,问题是:
function FormHelper(formId){
context = this; //<-------THIS WAS THE PROBLEM
this.form = $("#"+formId);
this.validate = function(){
$valid = true;
.......
should have been 本来应该
var context = this;
always something so simply... 总是这么简单...
thanks guys. 多谢你们。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.