问题
I have this odd behavior from Google MAPs autocomplete (or maybe I miss sth)... ideas? The odd:
- You enter sth into the input, e.g. 'London'
- You press [ENTER]
- You press [CLEAR] button
- You click into the 'input'
- You click outside the 'input'
....... and voila! The already cleared in step-3 text ('London' in our example) is right-back into the input...Why?
And here is the code:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false&libraries=places"></script>
</head>
<body>
<h1>MY FORM</h1>
<input type='text' id='myInput' size='50' placeholder='Enter text'>
<input type='button' value='clear' onclick='clearInput()'>
<script>
var myInput = document.getElementById('myInput');
var autocomplete = new google.maps.places.Autocomplete(myInput);
function clearInput(){
myInput.value = '';
}
myInput.addEventListener('change', function(){
console.log(event['target']['value']);
}, false);
</script>
</body>
</html>
回答1:
Answering the "why" complicated, because the source of the API-source is compressed, hard to say what's really going on there.
Of course the value of the input must be stored somewhere, because it must be restored in some cases(e.g. when you switch between the values of the dropdown).
Basically an autocomplete is listening for 4 events in the input:
focus, keydown, keyup, blur
None of these events will fire in your function, so the autocomplete may not recognize the new value.
Possible solution:trigger these events in your function:
function clearInput(){
google.maps.event.trigger(myInput,'focus');
myInput.value = '';
google.maps.event.trigger(myInput,'keydown',{keyCode:46});
google.maps.event.trigger(myInput,'keyup',{keyCode:46});
google.maps.event.trigger(myInput,'blur');
}
You may send a bug-report, this is not the expected behaviour and should be fixed.
来源:https://stackoverflow.com/questions/21617795/google-maps-autocomplete-bounces-back-already-cleared-text-odd-odd-odd