我有2个输入字段,而场所的自动完成功能仅在一个输入字段上起作用,我知道getElementById仅适用于1个ID,我尝试了getElementsbyClass,但这不起作用。
如何让它在两个输入字段中都起作用?
html代码
<script src="https://maps.googleapis.com/maps/api/js?sensor=false&libraries=places"></script>
<input id="autocomplete" name=origin type=text placeholder=Vertreklocatie>
<input id="autocomplete2" name=destination type=text placeholder=Bestemming>
js代码
function initialize() {
var input = document.getElementById('autocomplete');
var options = {componentRestrictions: {country: 'nl'}};
new google.maps.places.Autocomplete(input, options);
}
google.maps.event.addDomListener(window, 'load', initialize);
http://codepen.io/anon/pen/EjvWLE
提前致谢
最佳答案
您可以使用getElementsByClassName,但是需要遍历所有项目
这是更新的codepen。 http://codepen.io/anon/pen/WvEpKx
function initialize() {
var inputs = document.getElementsByClassName('autocomplete');
var options = {componentRestrictions: {country: 'nl'}};
for(var i = 0; i < inputs.length; i++){
new google.maps.places.Autocomplete(inputs[i], options);
}
}
google.maps.event.addDomListener(window, 'load', initialize);