簡體   English   中英

jQuery和Google地圖自動完成

[英]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
}

但是,此代碼有兩個問題:

  • 首先是我正在使用一個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演示

如果要使用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演示

希望這可以幫助。

為了找出正在調用哪個輸入元素,可以將事件傳遞給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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM