简体   繁体   中英

How to call function on click event in Jquery when the element is generated dynamically by script and access through class selector?

I am generating an anchor tag through script with class 'section-delete-btn':

<a class='section-delete-btn' role='button' id = '" + $("#section_name").val() + "'href='#'><i class='section-delete-btns fa fa-trash-o' aria-hidden='true'></i></a>

I am trying to access the a tag through class selector like this:

//delete a section
$('a').on('click','.section-delete-btn',function(){
  //get section name
  var section_name = $(this).attr('id');
  alert(section_name);
});

You are already using a delegate listener, but it will fail if, at the time of attaching the listener, your document does not have any a elements. Instead, use document :

$(document).on('click','a.section-delete-btn',function(){
  //get section name
  var section_name = $(this).attr('id');
  alert(section_name);
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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