无法获取未定义或null引用javascript的属性

时间:2014-12-11 18:09:01

标签: javascript events

当我从初始化函数启动函数时,我收到了消息

"无法获得财产' address_components'未定义或空引用"

我首先添加一个监听器

google.maps.event.addDomListener(window, 'load', initialize);

这是我的初始化函数

function initialize() {
   document.getElementById('autocomplete').value =   city()+','+countryName();  
   autocomplete = new google.maps.places.Autocomplete(
    /** @type {HTMLInputElement} */(document.getElementById('autocomplete')),
                                   {types: ['establishment','geocode']});

    fillInAddress();  --> this call does not work

    google.maps.event.addListener(autocomplete, 'place_changed', function() {
                    fillInAddress();  --> this call work when I change manually the value                   in                      the     field
                });
}

以下被调用函数在由上述侦听器(place_changed)

触发时有效
function fillinAddress()

     var place = autocomplete.getPlace();
     console.log(place);    --> this gives undefined  when call from initialize function

     for (var i = 0; i < place.address_components.length; i++) {  ..  --> this gives error 

     //Unable to get property 'address_components' of undefined or null reference

任何帮助?

1 个答案:

答案 0 :(得分:2)

您需要将自动完成功能传递给

这样的功能
function initialize() {fillinAddress(autocomplete)}
function fillinAddress(autocomplete){console.log(autocomplete);}