2012-04-20 42 views
0

我是JavaScript新手,想了解我的代碼正在發生什麼。我使用jQuery和OpenLayers來做一些web映射。在onLoad與onReady上下文中的Javascript範圍

這裏是代碼實施例1,其中在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,我的「映射」變量具有本地作用域。

在該函數中,我添加了一些圖層,生成控件等。所有工作和覆蓋在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') 
}); 
}); 

地圖變量仍未定義。爲什麼?我誤解了一個全球性的工作嗎?

我可以通過在onReady代碼塊中放入onLoad函數來獲得所有工作。我不知道爲什麼下面的工作:

$(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') 
    }); 
}); 

});

回答

0

您聲明的全局變量map正在工作的代碼片段。但jquery沒有方法onReady和onLoad。更好地創建將在$(document).ready()函數中執行的init()函數,不要混合$(document).ready和body.onload函數。使用init函數和document.ready事件。

+0

如果我這樣做,但我的動態生成的HTML不會被jQuery訪問嗎?當功能(在onLoad函數中編碼)被實現時,內容(當前在就緒函數中創建)可能存在也可能不存在。 – Jzl5325 2012-04-20 14:02:07

+0

它將被訪問爲什麼不可以。在ajax請求中使用回調。 – 2012-04-20 16:26:58