[英]jQuery and google maps auto complete
我讓Google Maps Autocomplete像這樣處理幾個input
標簽:
<input class="controls pac-input" id="pac-input" type="text" onfocus="geolocate()" placeholder="Type custom address" />
要啟用Google Maps自動完成功能,我需要以下代碼:
//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
}
但是,此代碼有兩個問題:
$(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);
});
}
如果要使用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);
});
});
希望這可以幫助。
為了找出正在調用哪個輸入元素,可以將事件傳遞給MyFunc()
。 使用$(this)
不會在該函數之外進行檢查以查看調用它的內容。
將addListener
更新為以下內容。
google.maps.event.addListener(autocomplete, 'place_changed', function (e) {
MyFunc(e);
});`
並將MyFunc()
更新為
function MyFunc(e) {
var fullAddress = autocomplete.getPlace().formatted_address;
var input = e;
//stuff that uses input
}
然后,您可以將input
用作變量,以保存有關要更新的元素的信息。 如果您執行console.log(input);
低於var input = e;
您將看到可用於獲取數據的項目列表。
您可能對設置var input = e;
最感興趣var input = e;
到var input = e.target;
代替。 這將使您輕松獲得有關輸入的信息。
示例: input.value
將返回相關輸入的值。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.