如何在克隆的元素上包含Google自动填充API?

时间:2020-01-13 08:15:34

标签: jquery googleplacesautocomplete

我已经以表格的形式包含了包含Google搜索API的多个字段。如果表单在页面加载时显示,则工作正常。我的表单中有一些字段,我在单击按钮时就将其克隆,这些表单字段也具有自动完成的API,但不适用于这些API。

这是我用来调用Google API的jquery代码

var autocomplete = {};
var autocompletesWraps = ['business_collections', 'exTab2', 'company_officer_details'];
var exTab2_form = { street_number: 'short_name', route: 'long_name', locality: 'long_name', administrative_area_level_1: 'short_name', country: 'long_name', postal_code: 'short_name' };
var business_collections_form = { street_number: 'short_name', route: 'long_name', locality: 'long_name', administrative_area_level_1: 'short_name', country: 'long_name', postal_code: 'short_name' };

var company_officer_details_form = { street_number1: 'short_name', route1: 'long_name', locality1: 'long_name', administrative_area_level_11: 'short_name', country1: 'long_name', postal_code1: 'short_name' };

function initialize() {

$.each(autocompletesWraps, function(index, name) {

    if($('#'+name).length == 0) {
        return;
    }

    autocomplete[name] = new google.maps.places.Autocomplete($('#'+name+' .autocomplete')[0], { types: ['geocode'] });
    autocomplete[name].setComponentRestrictions({'country': ['au']});   
    google.maps.event.addListener(autocomplete[name], 'place_changed', function() {

        var place = autocomplete[name].getPlace();
        var form = eval(name+'_form');

        for (var component in form) {
            $('#'+name+' .'+component).val('');
            $('#'+name+' .'+component).attr('disabled', false);
        }

        for (var i = 0; i < place.address_components.length; i++) {
            var addressType = place.address_components[i].types[0];
            if (typeof form[addressType] !== 'undefined') {
              var val = place.address_components[i][form[addressType]];
              $('#'+name+' #'+addressType).val(val);
            }
        }
    });
});
}

在上面的代码中,事情正在在页面上预定义的business_collections,exTab2中运行,并随页面加载而加载,但不适用于在页面加载时创建但又是克隆元素的company_nzl_details。

0 个答案:

没有答案