php - Unable to trigger modal from within jQuery DataTables
问题描述
I have a generic modal just before the closing body tag of my page. I use Javascript to show the modal when a button is clicked, passing data attribute values embedded within the button to the modal title, body and footer. This makes the modal dynamic. It works great, however, when I add the trigger button within jQuery DataTable, it fails to trigger the modal.
This is my modal:
<div class="modal fade" id="modal_confirm_action" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title"></h5>
<div class="pull-right m-l-15">
<button class="btn btn-danger btn-sm modal_close_btn" data-dismiss="modal" class="close" title="Close"> ×</button>
</div>
</div><!--/.modal-header-->
<div class="modal-body">
<!--render data via JS-->
</div>
<div class="modal-footer">
<a class="btn btn-sm btn-danger" role="button" id="action_url"> Yes, Continue </a>
<button data-dismiss="modal" class="btn btn-sm btn-secondary"> No, Cancel </button>
</div>
</div>
</div>
</div>
This is the button that triggers it:
<a class="btn btn-sm btn-danger text-white modal_trigger_confirm_action" data-title="Delete Post" data-msg="Sure to delete?" data-url="'.base_url('posts/delete_post/'.$id).'">Delete</a>
Note: I'm using server side processing with DataTables (and CodeIgniter), so the button above is inside my controller method, and rendered in one column, like this:
...
$row[] = '<a class="btn btn-sm btn-danger text-white modal_trigger_confirm_action" data-title="Delete Post" data-msg="Sure to delete?" data-url="'.base_url('posts/delete_post/'.$post_id).'">Delete</a>';
...
This is the JavaScript that opens the modal:
$('.modal_trigger_confirm_action').click(function() {
//get data value params
var title = $(this).data('title');
var msg = $(this).data('msg');
var url = $(this).data('url');
$('#modal_confirm_action .modal-title').text(title); //dynamic title
$('#modal_confirm_action .modal-body').html(msg); //dynamic body content
$('#modal_confirm_action .modal-footer #action_url').attr('href', url); //url to delete item
$('#modal_confirm_action').modal('show'); //show the modal
});
Clicking the Delete button within each row doesn't do anything. What am I doing wrong?
解决方案
因为按钮是动态生成的,而不是第一次加载时 DOM 的一部分,所以你需要触发点击动态生成的按钮,就像这样。
$(document).on( "click",".modal_trigger_confirm_action", function() { //logic here });
推荐阅读
- python - 为什么我会收到“语法警告对象不可调用;可能缺少逗号”?
- python - 用一定概率选择的特定数字填充矩阵
- html - 在使用 Heroku 和 goorm 作为环境部署的网站上显示图标和 alt 而不是照片
- amazon-web-services - 如何使用 AWS 深度学习 docker 容器
- reactjs - 组件方法中的未定义值
- python - EMR 和 MRJOB:TERMINATED_WITH_ERRORS:给定的 SSH 密钥名称无效
- python - 为什么使用链表而不是节点数组来构建图
- python - 下载图像总是损坏(Python urllib)
- python - 用 pandas 计算局部导数
- linux - 在 Google Colab 上运行 Docker