简体   繁体   English

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

[英]Can't add onclick listener to dynamically created element

I'm trying to implement a searchbar to search adresses and show the selected place on a map.我正在尝试实现一个搜索栏来搜索地址并在 map 上显示选定的位置。 When I type in the searchbar the results are showing in a dropdown, now I want to edit my map and other stuff when I click on a result.当我在搜索栏中输入时,结果显示在下拉列表中,现在我想在单击结果时编辑我的 map 和其他内容。

But I can't manage to add a listener to the elements (which are dynamically created when I got the results of the search), no matter what I try (addEventListener, JQuery, href) when I inspect the elements on my browser no listener is attached to any of them.但是当我检查浏览器上的元素时,无论我尝试什么(addEventListener,JQuery,href),我都无法设法为元素添加一个监听器(当我得到搜索结果时动态创建)没有监听器附在其中任何一个上。

Here is my html:这是我的 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>

And my JS:还有我的 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)
            })
    })
}

manually call initBarreRecherche() at the end of response.在响应结束时手动调用initBarreRecherche()

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

You are using jquery so instead of all 'onClick' syntax, or addEventListener, you can attach click handler like:您使用的是 jquery,因此您可以附加点击处理程序,而不是所有的“onClick”语法或 addEventListener:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM