我正在定义:
var inputs = document.getElementsByClassName('query');
与第一个元素一起使用,因为我们已经在页面上找到了它:
<input type="text" class="form-control query" placeholder="Enter location">
但是随后我通过input
向class query
添加了append()
,因此,当我这样做时:
$("body").on("click", ".addLocation", function(e){
e.stopPropagation();
$(".locationAdd").append('<input type="text" class="form-control query" placeholder="Enter location"><button type="button" class="addLocation btn btn-danger margin-top-20">Add location</button><hr>');
});
在这种情况下,var inputs
无法识别新的appended element
答案 0 :(得分:0)
这就是我的解决方法,基本上将所有内容放置在函数中,在开始时调用它,并在每次添加新元素时重新调用它。以下是页面上的完整代码,我要添加的是一个新的输入字段以添加新位置,因此我需要重新运行gmap代码:
setLocInput();
function setLocInput() {
var inputs = document.getElementsByClassName('query');
var autocompletes = [];
for (var i = 0; i < inputs.length; i++) {
var autocomplete = new google.maps.places.Autocomplete(inputs[i]);
autocomplete.inputId = inputs[i].id;
autocomplete.addListener('place_changed', fillIn);
autocompletes.push(autocomplete);
}
var locationsArray = [];
function fillIn() {
var place = this.getPlace();
var filtered_array = place.address_components.filter(function(address_component){
return address_component.types.includes("country");
});
var country = filtered_array.length ? filtered_array[0].long_name: "";
locationsArray.push(country);
$("#usp-custom-8").attr("value", locationsArray);
$("#usp-custom-8").attr("data-location", locationsArray);
}
}
$("body").on("click", ".addLocation", function(e){
e.stopPropagation();
$(".locationAdd").append('<input type="text" class="form-control query" placeholder="Enter location"><button type="button" class="addLocation btn btn-danger margin-top-20">Add location</button><hr>');
setLocInput();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&libraries=places&callback=getRelevantGoogleReviews"></script>
<input type="text" class="form-control query">