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
178 views
in Technique[技术] by (71.8m points)

javascript - How to make function like confirm

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

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

1 Reply

0 votes
by (71.8m points)

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

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

...