无法将 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 () {


    }

}

}


交互式爱情
浏览 130回答 2
2回答

一只名叫tom的猫

您使用的是 jquery,因此您可以附加点击处理程序,而不是所有的“onClick”语法或 addEventListener:$(dropdownResultats).on('click', 'li', event => {&nbsp; alert('some li clicked')})

SMILET

initBarreRecherche()在响应结束时手动调用。.then(adressesJSON => {&nbsp; &nbsp; ///....&nbsp; &nbsp; this.initBarreRecherche()})
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript