为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

交互式爱情 2022-06-16 14:48:26
我正在尝试实现一个搜索栏来搜索地址并在地图上显示所选地点。当我在搜索栏中输入时,结果会显示在下拉列表中,现在我想在单击结果时编辑我的地图和其他内容。但是我无法设法为元素添加一个监听器(当我得到搜索结果时动态创建),无论我在浏览器上检查元素时尝试什么(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 () {    }}}
查看完整描述

2 回答

?
一只名叫tom的猫

TA贡献1906条经验 获得超3个赞

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


$(dropdownResultats).on('click', 'li', event => {

  alert('some li clicked')

})


查看完整回答
反对 回复 2022-06-16
?
SMILET

TA贡献1796条经验 获得超4个赞

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


.then(adressesJSON => {

    ///....

    this.initBarreRecherche()

})


查看完整回答
反对 回复 2022-06-16
  • 2 回答
  • 0 关注
  • 129 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号