DEV Community

Seatgo
Seatgo

Posted on

How does Jquery monitor the click events of dynamically created elements?

During the process of using Jquery, we may dynamically create elements such as li/button, but we cannot listen to the created elements using the following methods:

var domains = [{"id":1,"name":"测试1"},{"id":2,"name":"测试2"},{"id":3,"name":"测试3"}];
$.each(domains,function(key,domain){
$("#link_child").append('<li id="'+domain.id+'">'+domain.name+'</li>');
});
$("#link_child li").click(function(){
var linkChild = $(this).attr("id");
$("#link_child li").removeClass("active");
$(this).addClass("active");
});
Enter fullscreen mode Exit fullscreen mode

We can use a new method to monitor clicks:

$(document).on('click','#link_child li',function(){
var id = $(this).attr("id");
$("#link_child li").removeClass("active");
$(this).addClass("active");
});
Enter fullscreen mode Exit fullscreen mode

Top comments (0)