问题描述
|
我有两个类和一个jquery调用问题。不幸的是,如果在一个类中调用一个方法,它会认为它是另一个。
在这里详细:
我正在写一个表格,用户可以在两个不同的输入字段中写下两个客户编号。该网站将通过jQuery AJAX查询每个客户编号,并显示客户编号的详细信息。
因此,我编写了一个类,用于不重复代码并将行为分配给每个输入字段。
CustomerData = function(settings){
this.name = \'\';
this.street = \'\';
this.zipcode =\'\';
this.town = \'\';
this.inputField = settings.inputfield;
this.init();
}
CustomerData.prototype.init = function() {
this.associateClassWithUi();
}
//here I assign the class with the inputfield via jQuery
CustomerData.prototype.associateClassWithUi = function() {
_this = this;
console.log(\"associate \" +this.inputField);
$(this.inputField).focus(function() {
console.log(\' focus on \'+_this.inputField);
});
$(this.inputField).blur(function() {
customerId = $(this).val();
console.log(\"blur event \" + _this.inputField);
if(customerId != \'\'){
_this.main(customerId);
} else {
_this.setEmpty();
_this.propertiesToUi();
}
});
}
我是这样定义类的:
var DataCustomer1 = new CustomerData({
inputField: \'#customer1\'
});
var DataCustomer2 = new CustomerData({
inputField: \'#customer2\'
});
console.log为我提供以下内容:
associate #customer1
associate #customer2
但是单击输入字段(#customer1和#customer2),我总会得到这个
focus on #customer2
focus on #customer2
focus on #customer2
当然,如果我更改实例化的顺序
var DataCustomer2 = new CustomerData(...);
var DataCustomer1 = new CustomerData(...);
他们每个人都认为他是客户1
我想念什么?
解决方法
使用var _this = this;否则,它将被全局声明并每次都被覆盖。
,当您声明不带var的变量时,该变量始终变为全局变量。如果您有以下HTML:
<ul>
<li id=\"customer1\">Customer 1</li>
<li id=\"customer2\">Customer 2</li>
</ul>
以下代码按预期工作:
CustomerData = function(settings){
this.inputField = settings.inputField;
this.init();
}
CustomerData.prototype.init = function() {
this.associateClassWithUi();
}
CustomerData.prototype.associateClassWithUi = function() {
var _this = this;
console.log(\"associate \" +this.inputField);
$(this.inputField).click(function() {
console.log(\'click on \'+_this.inputField);
});
}
var DataCustomer1 = new CustomerData({
inputField: \'#customer1\'
});
var DataCustomer2 = new CustomerData({
inputField: \'#customer2\'
});
您可以在此处找到有关JavaScripts变量的更多信息