我的代码如下...... 当点击动态添加的li时,onclick不会触发。但是当我对生成的li(555 Palm Dr,Burbank,CA,USA)进行硬编码并单击它会触发事件。
<input type="text" class="form-control-searchbox" placeholder="Search Here" id="searchbox" onkeypress="OnKeyPressAutoFill(this.value, event);">
<ul id="ul_autocomplete_result" class="sbOptions ui-menu ulZindex"></ul>
function OnKeyPressAutoFill(val, e) {
var event = window.event ? window.event : e;
console.log(event.keyCode)
if (gleble_counter < 0) gleble_counter = 0;
if (event.keyCode == 40) {
NextAddress(parseInt(gleble_counter));
gleble_counter = parseInt(gleble_counter) + 1;
} else if (event.keyCode == 38) {
gleble_counter = parseInt(gleble_counter) - 1;
PreviousAddress(parseInt(gleble_counter));
} else if (event.keyCode == 13) {
OnSelectLocation(parseInt(gleble_counter));
} else if (event.keyCode == 9) {
$("#div_addresses").html('');
$("#div_selected_address").html('');
$("#ul_autocomplete_result").html('');
} else {
gleble_counter = 0;
var availableTags = [];
$("#div_addresses").html('');
$("#div_selected_address").html('');
$("#ul_autocomplete_result").html('');
geocoder = new google.maps.Geocoder();
var location = val;
if (geocoder) {
geocoder.geocode({ 'address': location }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
for (var i = 0; i <= results.length - 1; i++) {
console.log(results[i].formatted_address);
$("#ul_autocomplete_result").append('<li onclick="OnLiSelect(' + i + ')" style="cursor:pointer" id="li_' + i + '">' + results[i].formatted_address + '</li>');
}
console.log(availableTags);
}
});
}
}
}
function OnLiSelect(val) {
$("#searchbox").val($('#li_' + val).text());
OnSelectLocation(val);
}
答案 0 :(得分:1)
由于$( "#ul_autocomplete_result" ).on( "click", "li", OnLiSelect );
元素是动态生成的,因此您需要使用事件委派。
OnLiSelect
将function OnLiSelect() {
var val = $(this).text(); // get val for 'this'
$("#searchbox").val(val);
OnSelectLocation(val);
}
功能更改为:
_.assign
此外,无需为动态添加的LI设置ID。