gpt4 book ai didi

javascript - Google Places Autocomplete - 点击模糊的第一个结果

转载 作者:行者123 更新时间:2023-11-29 19:12:43 25 4
gpt4 key购买 nike

我正在使用 Google Places Autocomplete,我只是希望它在表单字段中触发模糊事件并且存在建议时触发结果列表中顶部项目的点击事件。

var pac_input = document.getElementById('pick-auto');

                (function pacSelectFirst(input) {
// store the original event binding function
var _addEventListener = (input.addEventListener) ? input.addEventListener : input.attachEvent;

function addEventListenerWrapper(type, listener) {
// Simulate a 'down arrow' keypress on hitting 'return' when no pac suggestion is selected,
// and then trigger the original listener.
if (type == "keydown" || type == "blur") {
var orig_listener = listener;
listener = function(event) {
var suggestion_selected = $(".pac-item-selected").length > 0;
var keyCode = event.keyCode || event.which;
if ((keyCode === 13 || keyCode === 9) && !suggestion_selected) {
var simulated_downarrow = $.Event("keydown", {
keyCode: 40,
which: 40
});
orig_listener.apply(input, [simulated_downarrow]);
} else if(event.type === 'blur') {
pac_input.value =
$(".pac-container .pac-item:first-child").text();
// $(".pac-container").delegate(".pac-item:first-child","click",function(){
// console.log("success");
// });

$(".pac-container .pac-item:first-child").bind('click',function(){
console.log("click");
});

}
orig_listener.apply(input, [event]);
};
}

// add the modified listener
_addEventListener.apply(input, [type, listener]);
}

if (input.addEventListener)
input.addEventListener = addEventListenerWrapper;
else if (input.attachEvent)
input.attachEvent = addEventListenerWrapper;

})(pac_input);


$(function() {
var autocomplete = new google.maps.places.Autocomplete(pac_input);
});

最佳答案

试试这个:

演示:http://jsfiddle.net/q7L8bawe/

添加此事件:

$("#pick-auto").blur(function (e) {
if (e.which == 13) {
var firstResult = $(".pac-container .pac-item:first").text();

var geocoder = new google.maps.Geocoder();
geocoder.geocode({"address":firstResult }, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var lat = results[0].geometry.location.lat(),
lng = results[0].geometry.location.lng(),
placeName = results[0].address_components[0].long_name,
latlng = new google.maps.LatLng(lat, lng);

$(".pac-container .pac-item:first").addClass("pac-selected");
$(".pac-container").css("display","none");
$("#pick-auto").val(firstResult);
$(".pac-container").css("visibility","hidden");

}
});
} else {
$(".pac-container").css("visibility","visible");
}

});

关于javascript - Google Places Autocomplete - 点击模糊的第一个结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37584400/

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