在onLoad与onReady的上下文中的Javascript范围

时间:2012-04-20 13:03:40

标签: javascript jquery openlayers

我是javascript的新手,想要了解我的代码发生了什么。我正在使用jQuery和OpenLayers进行一些网络映射。

这是代码示例1,其中我的map变量是在onReady函数中创建的:

$(document).ready(function(){
    var map = new.OpenLayers.Map('map', options);
    $.get(my_python.cgi_script which returns an html table of available layers)
    });

As far as I understand,我的'map'变量有一个局部范围。

在该函数中,我添加了一些图层,生成控件等。所有工作都在OpenLayers文档中进行了介绍。我也使用jQuery的get方法调用python.cgi脚本,该脚本动态生成可用层的表。这一切都发生在上面的onReady。

我需要处理动态生成的内容,发现我需要将代码放入onLoad函数中。如果我将第二个代码块放入onReady函数中,则无法通过jQuery访问缩略图,因为呈现内容的顺序。

$(document).ready(function(){
    var map = new.OpenLayers.Map('map', options);
    //More code to dynamically generate a list of available layers, stored in a table
    $.get(my_python.cgi_script which returns an html table of available layers)
    });

$(body).onLoad(function(){
 $(img.thumbnail).bind('click', function(){
  var name = $(this).attr('layer_name_id')
  var layer = new OpenLayers.WMS(//all the stuff to add the layer, including name)
  map.addLayer('layer') //map undefined due to scope
});
});

在上面的块中,'map'在第二个变量中未定义。我理解为什么(范围)并决定地图需要是一个全局变量。然后我尝试了:

var map; //This is a global because it is defined outside of any functions?
$(document).ready(function(){
    map = new.OpenLayers.Map('map', options);
    //More code to dynamically generate a list of available layers, stored in a table
    $.get(my_python.cgi_script which returns an html table of available layers)
    });

$(body).onLoad(function(){
 $(img.thumbnail).bind('click', function(){
  var name = $(this).attr('layer_name_id')
  var layer = new OpenLayers.WMS(//all the stuff to add the layer, including name)
  map.addLayer('layer')
});
});

地图变量仍未定义。为什么?我是否误解了全球的运作方式?

通过将onLoad函数放在onReady代码块中,我能够完成所有工作。我不确定为什么以下是有效的:

$(document).onReady(function(){
    var map = new.OpenLayers.Map('map', options);
    //More code to dynamically generate a list of available layers, stored in a table
    $.get(my_python.cgi_script which returns an html table of available layers)

$(body).onLoad(function(){
 $(img.thumbnail).bind('click', function(){
  var name = $(this).attr('layer_name_id')
  var layer = new OpenLayers.WMS(//all the stuff to add the layer, including name)
  map.addLayer('layer')
  });
});   

});

1 个答案:

答案 0 :(得分:0)

您声明全局变量映射的代码段正在运行。但是Jquery没有onReady和onLoad的方法。最好创建将在$(document).ready()函数中执行的init()函数,不要混合$(document).ready和body.onload函数。使用init函数和document.ready事件。