简体   繁体   English

在 jQuery 事件处理程序中获取取消按钮上的确认对话框的结果

[英]Getting result of Confirm dialog on Cancel Button in jQuery event hander

On one side I have a form with submit/cancel buttons and the cancel has an onclick event (to do some cleanup) that is wrapped in a standard confirm dialog.一方面,我有一个带有提交/取消按钮的表单,并且取消有一个包含在标准确认对话框中的onclick事件(进行一些清理)。 All standard stuff.所有标准的东西。

But then I have a second script (and it MUST be a second script) that may only sometimes be loaded, that needs to add more tasks if the form is cancelled.但是后来我有第二个脚本(它必须是第二个脚本),它可能只是有时被加载,如果表单被取消,则需要添加更多任务。 So - I can listen for the onclick...所以 - 我可以听点击...

$( "#cancelBtn" ).on( "click", function(a) {
    // do more stuff...
});

but I only want to 'do more stuff' if the confirm around the onclick is OK.但如果 onclick 周围的确认没问题,我只想“做更多的事情”。 I am probably missing something stupidly simple but I have been at this all day and am about to give up!我可能遗漏了一些非常简单的东西,但我一整天都在做这件事,即将放弃! Can anyone point me in the right direction?任何人都可以指出我正确的方向吗?

Update: I can not change the form onclick code - it has to stay separate and as it now is.... so the confirm has to stay where it is.更新:我无法更改表单 onclick 代码 - 它必须保持独立,就像现在一样......所以确认必须保持原样。

Do it like this:像这样做:

$( "#cancelBtn" ).on( "click", function(a) {
    if (confirm('Are you sure you want to cancel?')) { // Standard confirmation message.
        // Pressed OK.
        // do more stuff...
    } else {
        // Pressed Cancel.
    }
});

Hope this helps.希望这可以帮助。

EDIT: Since you can't change the script performing form duty, a solution would be to overwrite the confirm() -function:编辑:由于您无法更改执行表单任务的脚本,解决方案是覆盖confirm()函数:

var _confirm = window.confirm;
window.confirm = function() {
    //catch result
    var confirmed = _confirm.apply(window,arguments);
    if (confirmed) {
        //confirm ok, do some tasks
    } else {
        //confirm cancelled, do some cleanup
    }
    //pass result on to the caller
    return confirmed;
};

http://jsfiddle.net/sofcuoab/ http://jsfiddle.net/sofcuoab/


put the tasks in the second script in将任务放在第二个脚本中

function doMoreStuff(){
    //more tasks
}

and call it in your confirm-clause like this并像这样在您的确认子句中调用它

if (typeof doMoreStuff === "function") {
    doMoreStuff();
}

or like this或者像这样

try {
    doMoreStuff();
}
catch(err) {
    //no second script loaded
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM