首页 > 解决方案 > 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"> &times;</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?

标签: phpjquerycodeigniterdatatables

解决方案


因为按钮是动态生成的,而不是第一次加载时 DOM 的一部分,所以你需要触发点击动态生成的按钮,就像这样。

$(document).on( "click",".modal_trigger_confirm_action", function() { //logic here });

推荐阅读