我想在我的函数之外使用变量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
。有什么东西我错过了或做错了吗?
boolChangeClass
谢谢,任何帮助都会得到满足。
答案 0 :(得分:4)
在更高的范围内声明当前值,以便它在那里可用,然后在内部函数中直接引用它(没有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调用返回数据并且你的回调已经执行之前,当前实际上不会有当前可用的电流 - 因此,你可能更好地包装任何其他功能你需要在function
中在回调结束时调用(如果这与您的情况相关)。
答案 1 :(得分:0)
您可以在$(document).ready()
var interval = null, 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;