javascript - How can I set click function on my current element? -


i trying dynamically set click function on role=button element add jquery. here code:

box_resources.foreach(function(box){   var title_button = '<a class="btn btn-primary btn-xs" style="margin:5px">' + title + '</a>';   var $list_item = $(title_button);   $list_item.click(function() {     console.log("hello");   });   $("#resources-master-list").append(title_button);  }); 

it seems way not work. have idea? thanks!

instead of adding new click handler each time add item dom, try using event delegation. understand how works, check out link more information.:

$(document).on("click", "[role='button']", function () {   alert("i'm clicked"); }); 

Comments