gpt4 book ai didi

javascript - 找不到原始元素时,如何单击另一个元素?

转载 作者:行者123 更新时间:2023-11-28 20:28:36 27 4
gpt4 key购买 nike

我创建了一个函数来随机选择付款(数字)。当找不到第一个选择(数字)时(尝试捕捉)然后我想选择另一个。

但我总是收到:

Failed: Cannot read property 'click'

发送8号时应该选择credit cart visa...

我做错了什么?元素确实存在,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');
}
}
};

最佳答案

这是一个 common problem in JavaScript ,在您的页面对象中,this 并不总是您期望的那样。例如,在此处的 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;
});

关于javascript - 找不到原始元素时,如何单击另一个元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40866495/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com