var start = new google.maps.places.Autocomplete(
(document.getElementById('start')), {
types: ['geocode']
});
<input id="start" placeholder="Where to begin?" type="text" />
<script type="text/javascript" src="http://maps.google.com/maps/api/js?libraries=places"></script>
我可以在文本字段中使Google地方信息自动完成。
我想要一个按钮来生成这些字段作为li并在每个字段中包括自动完成功能。这是一个没有自动完成功能的示例:
document.getElementById('addplace').addEventListener('click', function() {
addplace();
});
var j=1;
function addplace() {
var node = document.createElement("li");
node.innerHTML = "<input id='place" + j +"' placeholder='Pit stop " + j + "' onFocus='geolocate()' type='text' />";
document.getElementById("waypoints").appendChild(node);
j++;
}
<input type="submit" id="addplace" value="Add One!">
<ul id="waypoints"></ul>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?libraries=places"></script>
因此,生成的输入的ID为place1,place2等。
我尝试添加
var place"+j+" = new google.maps.places.Autocomplete(
(document.getElementById('place"+j+"')), {
types: ['geocode']
});
到addplace函数的定义中,但它似乎导致我所有的javascript被禁用(该地图不再显示)。不知道为什么;我不认为Google会阻止它。也许我犯了语法错误,或者放置“ + j +”不是命名变量的正确方法?
感谢您的帮助,将自动完成地点自动添加到每个生成的输入字段。
更新:我注意到这个问题,Google Places Autocomplete在动态生成的输入元素上不起作用,将对其进行研究以在此处尝试应用,但是我注意到使用了ajax以及其他可能比该示例更复杂的东西。也就是说,他们在答案中引用了http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js。如果我不用jquery就可以做到这一点,那对我来说可能会更好,或者更直接或更具有教育意义,因为我认为我的部分解决方案至少很接近/通过一些调整可能是正确的吗?
我想这就是您要寻找的东西:
1)。添加具有特定按钮的按钮id
。然后,使用任何元素(此处ul
带有id = "waypoints"
)包装所有自动完成输入。
2)。然后添加click event
到按钮,该按钮会生成带有dynamic的“自动完成输入” id's
。
3)。现在,为具有(here )的元素(here ul
)中所有这些(如果有的话)创建的输入创建click事件,并同时针对单击的Autcomplete Input创建autcomplete实例。id
id = "waypoints"
片段:
var totalAC = 0;
$(document).on('click', "#waypoints input[type=text]",function () {
var currentInp = $(this).attr("id");
var placeBox = new google.maps.places.Autocomplete(document.getElementById(currentInp));
});
$("#newAutocomplete").click(function(){
totalAC = $("#waypoints input").length;
totalAC = totalAC + 1;
var codeVar = "<li><input id='place" + totalAC + "' placeholder='Where to begin?' type='text' /></li>";
$("#waypoints").append(codeVar);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?libraries=places"></script>
<button id="newAutocomplete">Add One+</button>
<ul id="waypoints">
</ul>
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句