无法将 onclick 侦听器添加到动态创建的元素



我正在尝试实现一个搜索栏来搜索地址并在地图上显示所选位置。当我在搜索栏中键入结果时,结果会显示在下拉列表中,现在我想在点击结果时编辑我的地图和其他内容。

但是,无论我在浏览器上检查元素时尝试了什么(addEventListener,JQuery,href(,我都无法将侦听器添加到元素中(这些元素是在我获得搜索结果时动态创建的(。

这是我的html:

<div class="container p-3 text-center text-md-left clearfix">
<h1>Smart-bornes</h1>
<p>Je localise les smart-bornes les plus proches</p>
<div class="input-group dropdown mx-auto w-75 float-md-left">
<input id="localisation_barreRecherche" class="form-control" type="text" placeholder="Rechercher un lieu"/>
<button id="localisation_boutonRecherche" class="btn btn-light">Rechercher</button>
<div id="localisation_dropdownRecherche" class="dropdown-menu w-100"></div>
</div>
</div>
<div class="container p-3">
<div id="map"></div>
</div>

还有我的JS:

function initBarreRecherche(){
let barreRecherche = document.getElementById('localisation_barreRecherche');
let boutonRecherche = document.getElementById('localisation_boutonRecherche');
let dropdownResultats = document.getElementById('localisation_dropdownRecherche');
barreRecherche.onkeyup = function (event) {
console.log('onkeyup');
if(event.key === 'Enter'){
}else if(event.key === 'keydown'){
}else if(barreRecherche.value !== '') {
rechercheAdr(barreRecherche.value);
$(dropdownResultats).show();
}else{
$(dropdownResultats).hide();
}
};
boutonRecherche.onclick = function () {
}
}
function rechercheAdr(entree){
console.log('recherche');
return new Promise((resolve, reject) => {
fetch(rechercheURL + entree)
.then(resp => {
return resp.text();
})
.then(adressesJSON => {
let adresses = JSON.parse(adressesJSON);
let dropdownResultats = document.getElementById('localisation_dropdownRecherche');
//dropdownResultats.style.width = '100%';
dropdownResultats.style.zIndex = '10000';
let resultats = document.createElement('ul');
resultats.className = 'list-group';
if(adresses.length > 0){
for(let [key, adr] of Object.entries(adresses)){
let result = document.createElement('li');
result.className = 'list-group-item list-group-item-action';
result.href = 'javascript : resultOnClick(adr)';
result.style.paddingLeft = '5px';
result.style.paddingRight = '5px';
result.style.cursor = 'pointer';
//result.style.overflow = 'hidden';
result.innerText = adr.display_name;
result.addEventListener('click', () => console.log('onclick'));
resultats.appendChild(result);
}
}else{
console.log('aucun résultat');
let msgAucunResultat = document.createElement('li');
msgAucunResultat.style.paddingLeft = '5px';
msgAucunResultat.style.paddingRight = '5px';
msgAucunResultat.innerText = 'Aucun résultat';
resultats.appendChild(msgAucunResultat);
}
dropdownResultats.innerHTML = resultats.innerHTML;
console.log(adresses)
})
})
}

在响应结束时手动调用initBarreRecherche()

.then(adressesJSON => {
///....
this.initBarreRecherche()
})

您使用的是jquery,因此您可以附加点击处理程序,而不是所有的"onClick"语法或addEventListener,如:

$(dropdownResultats).on('click', 'li', event => {
alert('some li clicked')
})

最新更新