gpt4 book ai didi

javascript - jQuery 和谷歌地图自动完成

转载 作者:行者123 更新时间:2023-11-30 07:23:31 25 4
gpt4 key购买 nike

我让 Google map 自动完成处理多个 input 标签,如下所示:

 <input class="controls pac-input" id="pac-input" type="text" onfocus="geolocate()" placeholder="Type custom address" />

要启用 Google map 自动完成功能,我有以下代码:

//https://developers.google.com/maps/documentation/javascript/examples/places-autocomplete-addressform
$(document).ready(function () {

autocomplete = new google.maps.places.Autocomplete((document.getElementById('pac-input')), { types: ['geocode'] });

google.maps.event.addListener(autocomplete, 'place_changed', function () {
MyFunc();
});

});

然后,在 MyFunc() 函数中我执行我需要的操作:

function MyFunc() {
var fullAddress = autocomplete.getPlace().formatted_address;
var input = $(this);
//stuff that uses input
}

然而,这段代码有两个问题:

  • 首先是我使用一个 Id 来影响多个输入框(我有很多输入字段)。我尝试按类别选择,但失败并显示错误“未定义”。如何将该函数应用于输入字段集合?
  • 我怎么知道哪个字段被点击了?我尝试使用 jquery $(this) 但它无法正常工作。 jQuery 可以如何帮助我?

提前致谢!

最佳答案

为此,您不需要 jQuery。这是一个仅使用 javascript 的工作示例:

HTML:

<input class="autocomplete" id="ac1" placeholder="Enter your address" type="text"></input>
<input class="autocomplete" id="ac2" placeholder="Enter your address" type="text"></input>
<input class="autocomplete" id="ac3" placeholder="Enter your address" type="text"></input>

JavaScript:

var acInputs = document.getElementsByClassName("autocomplete");

for (var i = 0; i < acInputs.length; i++) {

var autocomplete = new google.maps.places.Autocomplete(acInputs[i]);
autocomplete.inputId = acInputs[i].id;

google.maps.event.addListener(autocomplete, 'place_changed', function () {
console.log('You used input with id ' + this.inputId);
});
}

JSFiddle demo

如果你想用 jQuery 做到这一点,那么你可以尝试这种方式:

$('.autocomplete').each(function() {

var autocomplete = new google.maps.places.Autocomplete($(this)[0]);
autocomplete.inputId = $(this).attr('id');

google.maps.event.addListener(autocomplete, 'place_changed', function () {
console.log('You used input with id ' + this.inputId);
});
});

JSFiddle demo

希望这对您有所帮助。

关于javascript - jQuery 和谷歌地图自动完成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28114925/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com