使用confirm()拦截jQuery.ajax()调用

时间:2011-06-17 10:08:08

标签: jquery confirm

我有一个通过jQuery绑定到链接的ajax调用,我想通过确认对话框拦截它。但是无论选择哪个选项,ajax调用都会触发(即使用户只是关闭对话框)。

有没有办法让确认在同步上下文中工作?

HTML:

<a href="#" class="removeItem delete">remove</a>

jQuery的:

$('.delete').click(function () {
    confirm('Are you sure you want to delete this?');
});


$('.removeItem').click(function (event) {
    event.preventDefault();

    $.ajax({
        url: 'myUrl',
        type: "POST",
        data: {
            // data stuff here
        },
        success: function () {
            // does some stuff here...
        }
    });
});

1 个答案:

答案 0 :(得分:86)

$('.removeItem').click(function (event) {
    if (confirm('Are you sure you want to delete this?')) {
        $.ajax({
            url: 'myUrl',
            type: "POST",
            data: {
                // data stuff here
            },
            success: function () {
                // does some stuff here...
            }
        });
    }
});