我正在尝试使用绑定(bind)到下拉列表的事件监听器来监听更改来调用 JavaScript 函数 (apiCall)。
我希望在从下拉列表中选择不同的菜单项时重新运行该函数,但是当我运行此代码时,事件监听器上会出现错误,提示“apiCall”未定义,即使显然就在上面。
有什么建议吗?
提前致谢。
// API CALL
var request = new XMLHttpRequest()
request.open('GET', base + forecast + key + city, true)
request.onload = function apiCall() {
var data = JSON.parse(this.response)
console.log(data)
string = JSON.stringify(data, null, 4);
app.innerHTML = string;
}
document.getElementById("locationList").addEventListener("change", apiCall)
//send request
request.send()
最佳答案
您分配给 window.onload
的函数是函数表达式,而不是函数声明。命名函数表达式的名称不会添加到周围范围,因此它只能在函数表达式本身本地使用。这意味着您稍后将无法在函数外部引用它:
function iAmAFunctionDeclaration() {
console.log("abc");
}
+function iAmAFunctionExpression() {
console.log("abc");
}
console.log(typeof iAmAFunctionDeclaration);
console.log(typeof iAmAFunctionExpression); // undefined (not added to the `window`).
相反,如果您可以将 apiCall
设为函数声明,您将能够访问其名称以便稍后执行它,并将其分配为回调:
function apiCall() {
console.log("performing api call");
}
window.onload = apiCall;
document.addEventListener("click", apiCall);
为了使您的 API 调用正常工作,您可以将 .bind()
您的 request
发送到您的 apiCall
函数,如下所示@Stratubas或者您可以将 this
关键字替换为 request
。这将允许您处理回调中的 this
所指的内容。有关在回调内部处理 this
的更多方法,请参阅 this answer和 this answer .
您可以阅读有关函数表达式的更多信息 here
关于javascript - 我正在尝试调用 JavaScript 函数,但无法访问它,因为显然它是 'undefined',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59816499/