gpt4 book ai didi

javascript - 附加时不触发 onclick 事件

转载 作者:行者123 更新时间:2023-12-03 05:11:43 25 4
gpt4 key购买 nike

我有下面的代码...当单击动态添加的 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);
}

最佳答案

<li>元素是动态生成的,您将需要使用事件委托(delegate)。

$( "#ul_autocomplete_result" ).on( "click", "li", OnLiSelect );

更改OnLiSelect功能:

function OnLiSelect() {
var val = $(this).text(); // get val for 'this'
$("#searchbox").val(val);
OnSelectLocation(val);
}

此外,无需为动态添加的 LI 设置 ID。

阅读:jQuery Event Delegation

关于javascript - 附加时不触发 onclick 事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41787137/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com