我想使用变量 current
在我的功能之外,我尝试了很多逻辑,但我刚刚得到 undefined variable
在控制台中。我是否遗漏或做错了什么?
var interval = null;
$(document).ready(function() {
interval = setInterval(updateDiv, 1000);
});
function updateDiv() {
var previous = "";
var postIDAPI = "http://localhost/test/json.php?shortURL=1";
$.getJSON(postIDAPI, function(json) {
var current = json.postid;
console.log('PostID : ', current);
$("#address").html(current);
if (previous !== current) {
clearInterval(interval);
};
});
};
var postID = current;
//here i want to use variable current
谢谢,如有任何帮助,我们将不胜感激。
最佳答案
在更高的范围内声明 current,以便它在那里可用,然后在内部函数中直接引用它(无需 var
语句),如下所示:
var interval = null;
var current;
$(document).ready(function() {
interval = setInterval(updateDiv, 1000);
});
function updateDiv() {
var previous = "";
var postIDAPI = "http://localhost/test/json.php?shortURL=1";
$.getJSON(postIDAPI, function(json) {
current = json.postid;
console.log('PostID : ', current);
$("#address").html(current);
if (previous !== current) {
clearInterval(interval);
}
});
}
var postID = current;
//here i want to use variable current
然而,正如评论者 Dave Newton 在下面指出的那样,在从 ajax 调用返回数据并且执行回调之前, current 此时实际上不可用 - 因此,您可能更好地包装您想要的任何附加功能需要在回调结束时调用的函数
中(如果这与您的情况相关)。
关于javascript - 在 jquery 中使用我的函数之外的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41493618/