Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/418.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 在函数之间传递变量_Javascript_Jquery - Fatal编程技术网

Javascript 在函数之间传递变量

Javascript 在函数之间传递变量,javascript,jquery,Javascript,Jquery,我有两个函数,一个在用户加载页面时发出Ajax请求,另一个每隔5秒左右运行一次以更新内容。使用第一个函数,我可以输出需要在第二个函数中使用的变量 function insert_last_ten() { $.ajax({ url: 'freeshout/chatlog.php', success: function(data) { $("#inner-wrap").html(data); var first_child =

我有两个函数,一个在用户加载页面时发出Ajax请求,另一个每隔5秒左右运行一次以更新内容。使用第一个函数,我可以输出需要在第二个函数中使用的变量

function insert_last_ten() {
    $.ajax({
       url: 'freeshout/chatlog.php',
       success: function(data) {
         $("#inner-wrap").html(data);
         var first_child = $("#inner-wrap :first-child").html();
         var value = first_child.match(/(value)=["']?((?:.(?!["']?\s+(?:\S+)=|[>"']))+.)["']?/);
         var realtime = value[2];
       }
     });
    }
基本上,我需要使用
realtime
在另一个函数中执行其他操作。为了简单起见,让我们假设这是第二个函数:

function update() {
    alert(realtime);
}

我如何才能使其工作?

成功
回调中,取消超时并使用更新的值启动一个新的超时。您可以通过参数将超时标识符传递给
insert_last_ten
,而
success
回调将通过闭包获取超时标识符:

function createUpdateTimer(value, interval) {
    return setTimout(
      function () {
        alert(value); // The created function knows what value is due to closure
      }, interval);
}

function insert_last_ten(timer) {
    $.ajax({
        url: 'freeshout/chatlog.php',
        success: function(data) {
            $("#inner-wrap").html(data);
            var first_child = $("#inner-wrap :first-child").html();
            var value = first_child.match(/(value)=["']?((?:.(?!["']?\s+(?:\S+)=|[>"']))+.)["']?/);
            var realtime = value[2];
            cancelTimer(timer); // This callbac knows what timer is due to closure
            timer = createUpdateTimer(realtime, 500);
        }
    });
}

// Start the timer:
var timer = createUpdateTimer('initial value', 500);

// Make ajax request:
insert_last_ten(timer);

注意,我刚刚开始熟悉JavaScript的好部分。此代码未经测试。

能否将
realtime
移出到更公开的范围?将
realtime
设为全局变量将是一种简单的方法。我该怎么做?我查看了jQuery文档并四处搜索,但无法真正了解您的意思=/@安德鲁:我用一个例子更新了我的答案。闭包不在jQuery文档中,因为它是JavaScript特性,而不是jQuery特性。