The first thing you have to think about is not which event has to be triggered, it's more important to know when to trigger the events.
The predictions will be loaded asynchronously, so you must wait until they are available. There will not fire any event when the predictions are available, but you may observe the DOMNodeInserted
-event of the body(the dropdown will be inserted there) and check if the nodes have the className 'pac-item' (it's the className of the items in the dropdown).
Then these events must be triggered on the input:
keydown
with keyCode:40
(to move to the first prediction in the dropdown)
keydown
with keyCode:13
(to select/activate the prediction)
focus
(to activate the input)
keydown
with keyCode:13
(to send the request)
Example:
var input = document.getElementById('pac-input'),
ac = new google.maps.places.SearchBox(input),
itemsloaded = google.maps.event
.addDomListener(document.body,
'DOMNodeInserted',
function(e){
if(e.target.className==='pac-item'){
//remove the listener
google.maps.event.removeListener(itemsloaded);
//trigger the events
google.maps.event.trigger( input, 'keydown', {keyCode:40})
google.maps.event.trigger( input, 'keydown', {keyCode:13})
google.maps.event.trigger( input, 'focus')
google.maps.event.trigger( input, 'keydown', {keyCode:13})
}
});
Note: In InternetExplorer the DOMNodeInserted
-event is supported since V9, in older versions and other browsers that didn't support this event you may check in intervals if there are .pac-item
present in the document.
Demo: http://jsfiddle.net/doktormolle/R8XdL/
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…