且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

javascript - 在回调中定义后,全局变量不在范围内?

更新时间:2021-10-24 06:24:13

您遇到的问题是 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.