Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I want to make custom confirm function.

so, I make a code like :

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

  var foot = document.createElement("div");

  var ok = document.createElement("div");
  ok.innerHTML = "OK";

  var cancel = document.createElement("div");
  cancel.innerHTML = "Cancel";

  foot.appendChild(ok);
  foot.appendChild(cancel);
  obj.appendChild(body);
  obj.appendChild(foot);

  document.getElementsByTagName("body")[0].appendChild(obj);

  ok.onclick = function(){
    return true;
  }

  cancel.onclick = function(){
    return false;
  }
}

or

returnValue = -1;
ok.onclick = function(){
  returnValue = true;
}

canacel.onclick = function(){
  returnValue = false;
}

while(true){
  if(returnValue !== -1) break;
}

return returnValue;

If this custom confirm function must get 1 parameter like original confirm function.

How can make the custom confirm function?

See Question&Answers more detail:os

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

1 Answer

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?");

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...