带有promise jquery的自定义确认按钮

时间:2016-01-18 00:02:13

标签: javascript jquery promise

我正在尝试在jquery中创建自定义确认弹出窗口,我创建了一个函数,在文本和两个按钮内请求时显示自定义警报:ok,cancel。:

www.

问题是我如何等到按钮点击并返回结果,如果确定,那么返回true?我以为我需要使用诺言并推迟。我该怎么做?

我不喜欢在插件JQuery UI - Dialog

中使用预先创建的确认按钮

1 个答案:

答案 0 :(得分:3)

对于这种类型的功能,承诺是一个好主意(它们不仅仅适用于异步!)。我们假设#confirm内有两个按钮被称为#ok#cancel

它的外观如下:

function showprompt(content) {
   var dfd = $.Deferred();

   $('#confirm').css('display','block')
   $('#msg').text(content);

   $('#confirm')
     //turn off any events that were bound to the buttons last 
     //time you called showprompt()
     .off('click.prompt') 

      //resolve the deferred
     .on('click.prompt','#ok',function() { dfd.resolve(); }) 

      //reject the deferred
     .on('click.prompt','#cancel',function() { dfd.reject(); });

   //return a the deferred's promise
   return dfd.promise();
}

然后你就像这样使用它:

showprompt(content).then(
   function() { alert('You clicked ok'); }, //promise resolved
   function() { alert('You clicked cancel'); }, //promise rejected
);