如何使功能像确认 [英] How to make function like confirm

查看:127
本文介绍了如何使功能像确认的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想制作自定义确认功能。

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

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

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

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

return returnValue;

如果此自定义确认功能必须获得1参数,如原始确认功能。

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

如何进行自定义确认功能?

How can make the custom confirm function?

推荐答案

就个人而言,我会使用第三方对话已经为此编写,写一个jQuery插件,或者至少拿一个更加面向对象的方法。按照目前的情况,您将在确认功能。 global-namespace-would-be-watluted>全局命名空间(其中确认函数已经存在)。

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).

另请注意,您无法暂停执行页面并等待 window.confirm 等响应。请参阅:如何重现等待 ; JavaScript的confirm()函数提供的功能?(接受的答案是你不能)。

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

在上面的例子中, resultCallback 是一个定义为响应确认框中的事件而执行操作的函数。

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

你可以传递一个对象消息和回调实现单个参数目标,但我怀疑真正的目标是替换 window.confirm ,其中(如上所述)表现不同。

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

这篇关于如何使功能像确认的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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