javascript - 在 jquery 中使用我的函数之外的变量

标签 javascript jquery


我想使用变量 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/

相关文章:

javascript - UserApp 用户搜索不返回任何结果

javascript - 使用 highcharts 处理 unix 时间戳

javascript - 检查元素是否在 jQuery 集合中

javascript - JQuery 重置所有其他子元素的 z-index

javascript - 等待数据返回,与 Angular 和 Breeze 同步调用

javascript - 在系统焦点使用Electron的任何地方打开一个窗口

javascript - 在大窗口尺寸上将所有 "px"值更改为 "vw"

javascript - 使用 minified.js 更新文本内容

jquery - HTML5 内容可使用 jQuery 编辑

jquery - Chart.js 如何在折线图中显示标签和图例的光标指针