简体   繁体   English

使用 jquery 动态生成链接上的 envent.target.id

[英]envent.target.id on dynamically generated links using jquery

I generated dynamic links.我生成了动态链接。 means when users click country Links that country's cities are shown.表示当用户单击国家链接时,会显示该国家/地区的城市。 I want envent.target.id of dynamiclly generated city link when it is clicked当点击它时,我想要动态生成的城市链接的 envent.target.id

 $(".countryName").children().on('click',()=>{ targetId=event.target.id; if(targetId=="country1"){ $("#cityName").html(""); $("#cityName").append('<a id="city1">city1</a>'); $("#cityName").append('<a id="city2">city2</a>'); } if(targetId=="country2"){ $("#cityName").html(""); $("#cityName").append('<a id="city3">city3</a>'); $("#cityName").append('<a id="city4">city4</a>'); } }); $(".cityName").children().on('click',()=>{ alert(event.target.id); });
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <div class="countryName" > <a id="country1">country1</a> <a id="country2">country2</a> </div> <div class="cityName" id="cityName" > </div>

The dynamically generated elements will not have any event bind to them.动态生成的元素不会绑定任何事件。 To bind any event with them, you have bind event after the element is created and placed, in DOM.要将任何事件与它们绑定,您必须在 DOM 中创建和放置元素后绑定事件。

The on() event listener creates city elements and place it in DOM. on()事件侦听器创建city元素并将其放置在 DOM 中。 At the end of listener, the dynamically generated children are getting event bind to them.在侦听器结束时,动态生成的子项将事件绑定到它们。

In case you want to bind event just once and not on each click, you can do one thing.如果您只想绑定一次事件而不是每次点击,您可以做一件事。 You can create and place all the elements in DOM.您可以在 DOM 中创建和放置所有元素。 And hide/show them, according to your need.并根据您的需要隐藏/显示它们。

 $(".countryName").children().on('click', () => { targetId = event.target.id; if (targetId == "country1") { $("#cityName").html(""); $("#cityName").append('<a id="city1">city1</a>'); $("#cityName").append('<a id="city2">city2</a>'); } if (targetId == "country2") { $("#cityName").html(""); $("#cityName").append('<a id="city3">city3</a>'); $("#cityName").append('<a id="city4">city4</a>'); } $(".cityName").children().on('click', () => { alert(event.target.id); }); });
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <div class="countryName"> <a id="country1">country1</a> <a id="country2">country2</a> </div> <div class="cityName" id="cityName"> </div>

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

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