Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
623 views
in Technique[技术] by (71.8m points)

jquery - Overriding Javascript Confirm() while preserving the callback


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
}

Now, what I want to do is call another function within the confirm function above, like so...

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

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?

For example...

$('#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>
});

Hopefully you understand what I mean.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

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.

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.

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();
    }
});

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...