我目前正在使用 playwright,并想撰寫一個包含內部箭頭函式的函式,類似于
async function setSearchDate(startDate='2021-12-07') {
....do something...
const startDateAttribute = await page.$(searchStartDate);
await startDateAttribute.evaluate(node => node.setAttribute('value', startDate));
但不知何故,內部箭頭函式看不到 startDate 值。我得到的錯誤是“elementHandle.evaluate: ReferenceError: startDate is not defined”。
如果我在箭頭函式中對startDate值進行硬編碼,則代碼運行良好。我怎樣才能傳遞那個值?
uj5u.com熱心網友回復:
evaluate在 page 中評估您的函式,而不是在您的代碼背景關系中。在頁面的背景關系中,沒有變數startDate(除非頁面定義了自己的window.startDate......)。
要傳遞引數,您必須使用...args:
await startDateAttribute.evaluate((node, startDate) => node.setAttribute('value', startDate), startDate)
請參閱檔案:Evaluating JavaScript(解釋這個確切的陷阱)和ElementHandle#evaluate.
uj5u.com熱心網友回復:
await startDateAttribute.evaluate(function(node) { node.setAttribute('value', startDate) });
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/375495.html
標籤:javascript 范围 剧作家
