为什么变量超出范围?

我的代码有一些“怪异”的问题。 它主要是西class牙语,但我相信你会得到。

$('#favoritos').live( 'pagecreate',function(event){ var favoritos = false; var fav_bus = ''; var fav_bici = ''; if (!isLocalStorageAvailable()) // Si no hay Local Storage para qué queremos entrar aqui $.mobile.changePage('#errorFavoritos', { transition: "pop" }); else{ $.each(localStorage, function(index){ var itemKey = localStorage.key(index); if (itemKey.indexOf('fav')){ // Si es un favorito var splitted = itemKey.split('-'); var tipo = splitted[0]; var numero = splitted[2]; favs_locales[itemKey] = { 'numero' : numero, 'id' : itemKey }; if (tipo == 'bus'){ favoritos = true; fav_bus = '
' + '

Parada ' + numero+ '

' + '
    '; pedirTiempos(numero).pipe(formatearTiempos).done(function(html){ fav_bus += html + '
'; }); } } }); // Ya tenemos los datos formateados console.log(fav_bus); if (fav_bus != ''){ $('#contentFavoritos').append( '

Paradas de Bus

' + '
' + fav_bus + '
'); } } });

这个问题出现在这个函数中:

 pedirTiempos(numero).pipe(formatearTiempos).done(function (html) { fav_bus += html; }); 

fav_bus后的fav_bus (在函数中)没关系,但是在函数之后的console.log(fav_bus)是错的。 就像它在function中没有改变一样。

我试图返回html但它输出的是[Object, object] (作为字符串)。

任何提示?

编辑:

我已经尝试将它存储到一个时态DOM元素中它没关系但是我无法输出那个HTML(虽然它就在那里)。

 pedirTiempos(numero).pipe(formatearTiempos).done(function(html){ fav_bus += html + '
'; $('#busTemp').html(fav_bus); }); if ($('#busTemp').length > 0){ console.log($('#busTemp').html());

没有输出!

从我的代码中可以看出, done看起来像异步调用。 所以你传递给它的函数最有可能在fav_bus += ' 。 这就是你没有看到变化的原因。

如果你把一个console.log放在你传递给done的函数内,另一个console.log就在调用完之后,你可能会看到外部的console.log先运行。

要解决此问题,使用fav_bus任何后续操作fav_bus需要在要传递done的匿名函数内done

此外,您无法从异步函数返回任何内容。 这就是你需要一个回调的原因,它将对异步结果进行操作。

编辑

将代码更改为for..in不应该真正破坏任何东西,除非你明确地使用循环索引。 您应该可以通过以下更改使其按原样运行:

 if (tipo == 'bus') { favoritos = true; fav_bus = '
'; pedirTiempos(numero).pipe(formatearTiempos).done(function (html) { fav_bus += html + '
'; // Ya tenemos los datos formateados if (fav_bus != '') { $('#contentFavoritos').append('

Paradas de Bus

' + '
' + fav_bus + '
'); } }); }

fav_bus变量是.live函数的本地变量,对.done不可见。

将代码移出匿名函数,这将是:

 function foo() { var a = 5; bar(); } function bar() { // "a" is out of scope here. a += 5; }