请提供帮助。
我正在尝试访问在 JQuery DataTable() 函数外部声明的对象变量。我已经为 Ajax 对象提供了设置,其中一个回调函数完成以在请求成功时执行。由于 async: false 已被弃用,我决定使用 setTimeout() 访问从外部回调函数初始化的变量。请查看我的代码以澄清我的问题。
var odata = {
ids: [],
dates: []
};
var table = $("#schedule");
table.DataTable({
ajax: {
url: "/api/MaintenanceSchedule",
dataSrc: "",
complete: function (data, status) {
if (status === "success") {
//some codes here
}
$("span.machineIds").each(function (index) {
machineIds[index] = $(this).attr("data-machine-id");//here the array output all elements if you check with console.log()
});
$("span.lastMaintained").each(function (index) {
lastMaintained[index] = $(this).attr("data-last-maintained");
});
//the odata properties below have assigned values as seen from the debugger window
odata = {
ids: machineIds,
dates: lastMaintained
};
}
//some other codes ...
//outside DataTable object
var checkMachineState = function (odata, interval) {
// some codes...
}
const INTERVAL = 45000;
setTimeout(checkMachineState(odata,INTERVAL),5000);//odata properties are still not initialized as seen from the debugger
调试器显示如下
odata: 对象 日期: [] ID:数组(0) 长度:0 原型(prototype):数组(0) 原型(prototype):对象
最佳答案
这里的问题是 setTimeout
函数正在立即运行函数 checkMachineState()
而不是等待 5 秒。
那是因为 setTimeout
需要一个函数名(即只有 checkMachineState
而没有 ()
)。但是输入的是一个函数表达式(一个关闭()
的函数,遇到javascript会运行并解析为一个值)。
但是您需要有括号才能传递参数odata
和INTERVAL
。解决方案是将您的函数包装在一个匿名函数声明中(声明一个函数通常不会导致它运行),如下所示:
setTimeout(() => {checkMachineState(odata,INTERVAL)},5000);
运行下面的代码看看我的意思:
console.log("start");
setTimeout(console.log("This runs immediately because of the ()"),10000); //even if delay is 10 seconds
setTimeout(() => console.log("This waits 5 seconds before firing"), 5000);
我用 ES6 箭头符号写了上面的内容。也可以写成:
setTimeout(function() {checkMachineState(odata,INTERVAL)},5000);
关于javascript - 如何访问在 Ajax 回调函数中初始化的变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56202468/