简体   繁体   English

当元素由脚本动态生成并通过 class 选择器访问时,如何在 Jquery 中的单击事件上调用 function?

[英]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':我正在使用 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:我正在尝试通过 class 选择器访问 a 标签,如下所示:

//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.您已经在使用委托侦听器,但如果在附加侦听器时您的文档没有任何a元素,它将失败。 Instead, use document :相反,使用document

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

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

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