access javascript variable outside scope
I have
jQuery(document).ready(function()
{
jQuery.get('data/php/traces_pos.csv', function(data) { var routes = jQuery.csv()(data); });
//if I use here
for (i=0;i<=routes.length;i++){}
// javascript says route undefined
}
How do I access the routes which is a array 开发者_开发问答of arrays
Define routes outside the callback:
var routes;
jQuery.get('data/php/traces_pos.csv', function(data) { routes = jQuery.csv()(data); });
You need to wait until routes has been set. I'm using a function and passing in routes
as a parameter:
jQuery(document).ready(function()
{
jQuery.get('data/php/traces_pos.csv', function(data) {
var routes = jQuery.csv()(data);
performRoutes(routes);
});
});
//if I use here
function performRoutes(routes) {
for (i=0;i<=routes.length;i++){
// routes
}
}
You have to define routes outside of either function, as such:
var routes;
jQuery(document).ready(function()
{
jQuery.get('data/php/traces_pos.csv', function(data) { routes = jQuery.csv()(data); });
//if I use here
for (i=0;i<=routes.length;i++){}
// routes is no longer undefined
}
Moving the declaration of routes
outside the jQuery.get
call will make it visible to your for loop -- but beware that your for loop runs before the callback is called, so routes
will not have been set yet.
Anything you do that depends on the result of an asynchronous get must be either inside the callback function or in code that is called from within the callback function. In the latter case, you can pass your routes as a parameter at the function call -- there is no need to widen the variable's scope.
精彩评论