在javascript中关闭

时间:2011-05-24 10:32:46

标签: javascript google-maps-api-3

function initialize(final) 
{
    if (GBrowserIsCompatible()) {
             ................................................
        }

        var address_array = final.split('~');

        for (var count = 0; count < address_array.length; count++) {
            if (geocoder) {
                geocoder.getLatLng(
        address_array[count],
        makeTheFunction(address_array, count)
    );
            }
        }

  }



  function makeTheFunction(array, thisCount) {
      return function (point) {
          if (!point) {
              alert(array[thisCount] + " not found");
          }


          else {
              var marker = new GMarker(point);
              map.addOverlay(marker);
              GEvent.addListener(marker, "click", function () {
                  marker.openInfoWindowHtml(array[thisCount] + "</b>");
              });
          }
      };
  }

我的问题是我无法从else部分访问array[thisCount],尽管可以从if块访问..即alert(array[thisCount] + " not found");正在运行 请帮忙

3 个答案:

答案 0 :(得分:0)

function makeTheFunction(array, thisCount) 
{         
          if (!point) 
          {
              alert(array[thisCount] + " not found");
          }
          else 
          {
              var marker = new GMarker(point);
              map.addOverlay(marker);
              GEvent.addListener(marker, "click", function () {
                  marker.openInfoWindowHtml(array[thisCount] + "</b>");
              });
          }
      return point;
  }

答案 1 :(得分:0)

else 块或“click”处理程序中是否无法访问?如果您只能在“click”处理程序中获取array / thisCount,您是否尝试复制这些变量?这可能是上下文的问题吗?如果您的数组在 else 块中可见,请尝试此操作:

function makeTheFunction(array, thisCount) {
  return function (point) {
      if (!point) {
          alert(array[thisCount] + " not found");
      }


      else {
          var item = array[thisCount];
          var marker = new GMarker(point);
          map.addOverlay(marker);
          GEvent.addListener(marker, "click", function () {
              marker.openInfoWindowHtml(item + "</b>");
          });
      }
  };

}

答案 2 :(得分:0)

我建议addListener函数出现问题。在提供的代码中,侦听器中的thisCount应该在makeTheFunction函数中具有对thisCount的闭包。

以下模拟已发布的代码:

<script type="text/javascript">

function init() {
  var count = 'the count';
  partTwo(makeFn(count));

  function makeFn(thisCount) {
    return function() {

      // Shows 'thisCount: the count'
      alert('thisCount: ' + thisCount);
      document.getElementById('btn0').addEventListener('click',
        function(){alert('thisCount: ' + thisCount);}, false);
    }
  }
}

function partTwo(fn) {
  fn();
}

window.onload = function() {
  init();
};

</script>

<!-- Shows 'thisCount: the count' -->   
<button id="btn0">Button 0</button>

然而,它使用浏览器addEventListener附加了侦听器,而不是显然是自定义addListener