How to combine two jQuery functions?

2019-07-24 15:12发布

The first function (can be found at http://nadiana.com/jquery-confirm-plugin):

 $('#confirm').confirm(
{
    msg: 'You are about to delete gallery and all images related to that gallery. Are you sure?<br>',
    buttons: {
    separator: ' - '
    }
}
);

Basically there is Yes/No question, and if you answer Yes, it proceed further.

Second function:

$(document).ready(function() {
    $('#load').hide();
});
$(function() {
    $(".delete").click(function() {
        $('#load').fadeIn();
        var commentContainer = $(this).parent();
        var id = $(this).attr("id");            
        var string = 'id='+ id ;

        $.ajax({   
            url: "<?php echo site_url('gallery/delete_image') ?>",
            type: "POST",
            data: string,
            cache: false,
            success: function(){
                commentContainer.slideUp('slow', function() {$(this).remove();});
                $('#load').fadeOut();
            }   
        });
        return false;
    });
});

This function is for deleting images. How can I combine this two functions? First I want question to be asked, and if Yes is clicked to proceed with deleting.

2条回答
我想做一个坏孩纸
2楼-- · 2019-07-24 16:00

According to the documentation you linked to, you simply use the same selector for both your action and your confirm:

$(document).ready(function() {
    $('#load').hide();

    $(".delete").click(function() {
        $('#load').fadeIn();
        var commentContainer = $(this).parent();
        var id = $(this).attr("id");            
        var string = 'id='+ id ;

        $.ajax({   
            url: "<?php echo site_url('gallery/delete_image') ?>",
            type: "POST",
            data: string,
            cache: false,
            success: function(){
                commentContainer.slideUp('slow', function() {$(this).remove();});
                $('#load').fadeOut();
            }   
        });
        return false;
    });



    $('.delete').confirm(
    {
        msg: 'You are about to delete gallery and all images related to that gallery. Are you sure?<br>',
        buttons: {
        separator: ' - '
        }
    });
});
查看更多
贼婆χ
3楼-- · 2019-07-24 16:03

It's more a question that is related to the plugin you choose but as you can read in the manual of the plugin it's just adding both events to the same element and the plugin does the rest.

From the site:

To put it simply, it saves a copy of all event handlers bound to the element, unbinds them and binds itself instead. A confirmation dialog is displayed when the user triggers the action. If the user chooses to proceed with the action, it rebinds the handlers again and triggers the event. If the user chooses to cancel the action, the dialog disappears.

So what you need to do is something like:

$('#delete').click(function(){ ... });
$('#delete').confirm();

Of course you can extend this at need.

查看更多
登录 后发表回答