本文介绍了javascript - 在回调中定义后,全局变量不在范围内?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时删除!!

每当我尝试运行类似以下内容时,firebug会告诉我标记是未定义的行for(var i = 0 ...

whenever i try to run something like the following, firebug tells me that "markers is undefined" at the line "for (var i=0 ..."

但是我在右上角声明了标记为全局变量...?

but i declared markers as a global variable at the top right...?

var markers;
function load() {

  $.get("phpsqlajax_genxml.php", function(data) {
    markers = data.documentElement.getElementsByTagName("marker");
  });

  for (var i = 0; i < markers.length; i++) {
    var name = markers[i].getAttribute("name")
    //do more stuff
    }
}

但是当我这样做,

var markers;
function load() {

  $.get("phpsqlajax_genxml.php", function(data) {
      markers = data.documentElement.getElementsByTagName("marker");
      makeMarkersWithXMLinfo();
  });

  function makeMarkersWithXMLinfo() {
      for (var i = 0; i < markers.length; i++) {
             var name = markers[i].getAttribute("name")
             //do more stuff
      }
  }
}


我甚至不将markers作为参数传递给我的makeMarkersWithXMLinfo 。但它的工作原理。这是怎么回事? thnx

i'm not even passing "markers" as an argument to my makeMarkersWithXMLinfo() function. but yet it works. what's going on? thnx

推荐答案

您遇到的问题是 get 异步操作。因此,在 get 之后成功回调之前,运行。例如。 (见注释):

The problem you're having is that get starts an asynchronous operation. So your code immediately following the call to get happens before the success callback on the get is run. E.g. (see the comments):

var markers;
function load() {

  // ===> This happens FIRST
  $.get("phpsqlajax_genxml.php", function(data) {
    // ===> This happens THIRD, some time after `load` returns
    markers = data.documentElement.getElementsByTagName("marker");
  });

  // ===> This happens SECOND
  for (var i = 0; i < markers.length; i++) {
    var name = markers[i].getAttribute("name")
    //do more stuff
    }
}

你的第二个例子是正确的编码方式(虽然我建议完全避免使用全局),因为只有在GET完成后才使用标记

Your second example is the correct way to code it (although I'd recommend avoiding a global entirely), because you're using markers only after the GET has completed.

这篇关于javascript - 在回调中定义后,全局变量不在范围内?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

1403页,肝出来的..

09-07 02:16