加载后将jquery处理程序附加到modal

加载后将jquery处理程序附加到modal,jquery,Jquery,单击#显示删除,我正在加载一个模式。在这个模式中(这是一个远程页面),我想为点击#delete user附加一个处理程序。这个处理程序根本不工作,按钮什么也不做 如果我将deleteAccount函数放在实际的模式页面(m_delete_user.php)中,处理程序会工作,但是为了方便和其他操作,我希望将它们保存在index.php中 inside index.php: // show delete user modal var showDelete = function() { $(

单击#显示删除,我正在加载一个模式。在这个模式中(这是一个远程页面),我想为点击#delete user附加一个处理程序。这个处理程序根本不工作,按钮什么也不做

如果我将deleteAccount函数放在实际的模式页面(m_delete_user.php)中,处理程序会工作,但是为了方便和其他操作,我希望将它们保存在index.php中

inside index.php:

// show delete user modal
var showDelete = function() {
    $('#show-delete').on('click', function () {
        var $form = $(this).closest('form');
        var username = $form.find("select[name=account_username]").val();

        //open the modal with the username value
        $('#modal-ajax').load('/spc_admin/modals/m_delete_user.php?username='+username);
        $('#modal-ajax').modal('show');

        // initialize the button handler
        deleteAccount();                
    });
}

// delete user (modal delete button)
var deleteAccount = function() {
    $('#delete-user').on('click', function () {
        var $form = $(this).closest('form');
        $.ajax({
            type: 'post',
            url: '/spc_admin/process/p_delete_user.php',
            data: $form.serialize(),
            dataType : 'json'
        }).done(function (response) {
            if (response.success) {

... and continued

您必须等待
.load()
操作完成,因为它是异步的。您可以使用传递给
.load()
的完成函数完成此操作,并使用完成函数触发deleteAccount处理程序的安装

// delete user (modal delete button)
var deleteAccount = function() {
    $('#delete-user').on('click', function () {
        var $form = $(this).closest('form');
        $.ajax({
            type: 'post',
            url: '/spc_admin/process/p_delete_user.php',
            data: $form.serialize(),
            dataType : 'json'
        }).done(function (response) {
            if (response.success) {

... and continued

// show delete user modal
var showDelete = function() {
    $('#show-delete').on('click', function () {
        var $form = $(this).closest('form');
        var username = $form.find("select[name=account_username]").val();

        //open the modal with the username value
        // ==> deleteAccount added as a completion function here
        $('#modal-ajax').load('/spc_admin/modals/m_delete_user.php?username='+username, deleteAccount);
        $('#modal-ajax').modal('show');

    });
}

为什么要使用
var showDelete=function()
而不是
function showDelete()