Javascript 在函数之间传递变量
我有两个函数,一个在用户加载页面时发出Ajax请求,另一个每隔5秒左右运行一次以更新内容。使用第一个函数,我可以输出需要在第二个函数中使用的变量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 =
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特性。