我创建了一个随机选择付款的功能(号码)。当找不到第一个选择(数字)时(尝试捕获)然后我想选择另一个。
但我总是收到:
失败:无法读取属性'click'
发送号码8时,应选择信用卡签证......
我做错了什么?元素真的存在,id也是正确的:
CheckoutPage3.prototype.selectPayment = function (number) {
if (number == 1) {
try {
this.elementPaymentPaypal.click().then(function () {
return 1;
}, function (err) {
console.log("payment not found, select new");
this.elementPaymentCreditCard.click();
this.elementCreditVISA.click();
number = 2;
});
}
catch (err) {
console.log('error occured');
}
}
else if (number == 2) {
this.elementPaymentCreditCard.click();
this.elementCreditVISA.click();
number = 2;
} else if (number == 3) {
this.elementPaymentCreditCard.click();
this.elementCreditMasterCard.click();
number = 3;
}
else if (number == 4) {
try {
this.elementPaymentCreditCard.click();
this.elementCreditAmericanExpress.click().then(function () {
number = 4;
}, function (err) {
console.log("payment not found, select new");
this.elementCreditVISA.click();
number = 2;
});
}
catch (err) {
console.log('error occured');
}
}
else {
try {
this.elementPrePayment.click().then(function () {
number = 5;
}, function (err) {
console.log("payment not found, select new");
this.elementPaymentCreditCard.click();
this.elementCreditVISA.click();
number = 2;
});
}
catch (err) {
console.log('error occured');
}
}
};
答案 0 :(得分:2)
这是common problem in JavaScript,在您的网页对象中, this
并不总是您期望的。例如,在此处的promise promise函数中:
this.elementPaymentPaypal.click().then(function () {
return 1;
}, function (err) {
console.log("payment not found, select new");
this.elementPaymentCreditCard.click(); // < HERE
this.elementCreditVISA.click(); // < and HERE
number = 2;
});
this
不再引用“当前”页面对象的实例。
解决问题的常用方法是在父作用域中保存对this
的引用:
CheckoutPage3.prototype.selectPayment = function (number) {
var self = this;
if (number == 1) {
try {
// ...
然后使用self
代替this
:
this.elementPaymentPaypal.click().then(function () {
return 1;
}, function (err) {
console.log("payment not found, select new");
self.elementPaymentCreditCard.click();
self.elementCreditVISA.click();
number = 2;
});