How to make function like confirm

后端 未结 2 1828
南方客
南方客 2020-12-12 03:08

I want to make custom confirm function.

so, I make a code like :

function confirm(msg){
  var obj = document.createElement(\"div\");
  var body = doc         


        
相关标签:
2条回答
  • 2020-12-12 03:29

    You can't have your confirm function halt until a value is found, otherwise the whole page would freeze. What you need in this case is to provide a callback to execute once either of the buttons is clicked (if you can not pass it as argument for any reason, you'd have to use a global var, or maybe a queue):

    var queue = [];
    function confirm(msg){
      ...
      var callback = queue.shift();
      ok.onclick = function(){
        callback(true);
      }
    
      cancel.onclick = function(){
        callback(false);
      }
    }
    

    You use it this way:

    queue.push(function(returnValue) {
        if ( returnValue ) {
           // Code for "yes"
        }
        else {
           // Code for "no"
        }
    });
    confirm("Are you sure?");
    
    0 讨论(0)
  • 2020-12-12 03:34

    Personally, I would use a third-party dialog already written for this, write a jQuery plugin, or at least take a more object-oriented approach. As it stands, you are putting a confirm function in the global namespace (where a confirm function already exists).

    Also note that you can't halt execution of the page and wait for a response like window.confirm can. See: How can I reproduce the "wait" functionality provided by JavaScript's confirm() function? (where the accepted answer is "you can't").

    The available way of performing such a task is to use a callback:

    function customConfirm(message, resultCallback){
    
        ok.onclick = function(){
    
          // note that you can pass whatever you want to the callback
          // you are not limited to one parameter.
          resultCallback(true);
        }
    
        cancel.onclick = function(){
           resultCallback(false);
        }
    }
    

    In the above example, resultCallback is a function defined to perform an action(s) in response to events in your confirmation box.

    You could pass an object with both the message and the callback to achieve the single parameter goal, but I suspect the real goal is to replace window.confirm which (as stated) behaves differently.

    { message: "foo", callback: function bar(status){ alert(status); } }
    
    0 讨论(0)
提交回复
热议问题