覆盖Javascript确认(),同时保留回调 [英] Overriding Javascript Confirm() while preserving the callback

查看:214
本文介绍了覆盖Javascript确认(),同时保留回调的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



至此,我要覆盖jQuery插件中的标准js confirm()函数。我已经弄清楚如何使用下面的简单的功能布局。


To the point, I want to override the standard js confirm() function within a jQuery plugin. I have figured out how to do it with the simple function layout below.

function confirm(opts) {
   //code
}



现在,我想做的是调用确认功能,如此...

function confirm(opts) {
   openModal(opts);
}

openModal 函数将打开一个自定义模式窗口与消息和所需的按钮。 $ c>或 cancel submit 返回true, cancel 返回false。但现在,如何基于按钮点击返回true或false?

The openModal function will open a custom modal window with the message and required buttons. The buttons are both <span> with the id of either submit or cancel. submit returns true and cancel returns false. But now, how do I return either true or false based on the button clicked?

例如...

$('#openModal').live('click', function() {
   var opts = { title:'Modal Title', message:'This is a modal!' };
   var resp = confirm(opts);
   if(resp) 
      // user clicked <span id="submit"></span>
   else 
      // user clicked <span id="cancel"></span>
});

希望你明白我的意思。

推荐答案

可能,但不完全如你所述。使用确认函数的典型方式是:

This is possible but not exactly as you describe. The typical way the confirm function is used is:

if(confirm("Are you sure you want to submit this form?")) {
    form.submit();
}

在上面的示例中,按下按钮与脚本同步返回。在函数中暂停执行,直到按下按钮。

In the above example, the button press is returned synchronously to the script. Execution is paused within the function until a button is pressed.

模态对话框只是HTML网页的整个内容的叠加。

A "modal dialog" is just an overlay over the entire contents of an HTML web page. To the browser, buttons within such an overlay work the same way as buttons anywhere else within that page do.

由于JavaScript会以异步方式处理这种按钮点击(即使用回调函数处理事件)而不是同步,您尝试的方法将无法工作。

Since JavaScript handles such button clicks asynchronously (i.e. using callback functions to handle events) rather than synchronously, the approach you are attempting will not work.

您需要更改使用confirm函数的代码的所有部分,看起来像这样:

You would need to change all parts of the code that use the confirm function to look like this:

confirm("Are you sure you want to submit this form?", function(result) {
    if(result) {
        form.submit();
    }
});

这将像使用jQuery本身注册一个事件处理程序一样工作。脚本执行会立即继续,跳过匿名函数中的所有代码。稍后,浏览器将通过您在confirm函数中注册的JavaScript事件处理程序间接调用该函数,其目的是使用 true 或<$ c $来调用回调函数c> false

This would work just as registering an event handler with jQuery itself does. Script execution continues immediately, skipping past all the code in the anonymous function. Later, the browser will call that function indirectly through a JavaScript event handler that you register within the confirm function, its purpose to call the callback function with either true or false as appropriate.

这篇关于覆盖Javascript确认(),同时保留回调的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆