[英]How to create an event listener using JQuery?
I am new to JQuery.我是 JQuery 的新手。 I know this question is a little bit confusing but, maybe this explanation might help:
我知道这个问题有点令人困惑,但是,也许这个解释可能会有所帮助:
I have a dynamic <li>
tag generated by JavaScript with dynamic Id's, I just want to add an event listener to every new generated <li>
tag.我有一个由 JavaScript 生成的带有动态 Id 的动态
<li>
标签,我只想为每个新生成的<li>
标签添加一个事件侦听器。 Maybe in a way like this ?也许像这样? I know this doesn't work.
我知道这行不通。
<li id="2" onadded="createEvent()"></li> //new generated <li> tag
<li id="1" onadded="createEvent()"></li> //the 1st generated <li> tag
<script>
function createEvent(){
//event here
}
</script>
How can I achieved that ?我怎样才能做到这一点? or any possible solution?
或任何可能的解决方案? Thanks in advance.
提前致谢。
Using $.fn.on function to bind event for parent of li , and use selector "li" for li, then your dynamic generated li elment will reponse the event.使用 $.fn.on 函数为 li 的父绑定事件,并为 li 使用选择器“li”,然后您的动态生成的 li elment 将响应该事件。 Like following:
像下面这样:
//$(document) can be replaced by $(parentsOfLi) , .i.e: $("ul") or $("#" + idOful)
$(document).on("click", "li", function () {
//do your process here
//alert($(this).text());
//$(this).parent().append("<li></li>")
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.