从自定义提醒返回值

时间:2012-01-14 22:05:24

标签: javascript override alert

  

可能重复:
  How to create TRULY modal alerts/confirms in Javascript?

TL; DR:我已使用基于HTML的自定义HTML重写了默认的alert()函数。我希望新对话仍然阻止执行,并在对话框中获取按钮,以便从调用true返回falsealert()以用于逻辑(并继续执行)。 / p>


我正在尝试实现一个自定义警告框,它使用具有相同(或类似)功能的精美主题框替换默认浏览器警报。

我已阅读this个问题,我正在使用this answer中提供的解决方案(针对同一问题)。我现在要做的是获取被覆盖的警报以返回真值或假值,以便在if()语句中使用,具体取决于是否点击了OKCancel

if(alert('Confirm?') {
    // Do stuff
}

但是,由于有自定义HTML而不是正常警报,我不能这样做有两个原因:

  • 我无法从替换对话框中的按钮返回值(点击与$.on()绑定的事件),因为我不知道如何操作。
  • 据我所知,我无法使用此警报阻止程序流程。

我已将$.on()个事件绑定到替换对话框中隐藏框的CancelOK按钮。这些工作正常,但我现在遇到的问题是在单击按钮时返回值 ,以便执行将停止,直到用户采取操作为止。

HTML:

<div class="alert background"></div>

<div class="alert box">
    <div class="message"></div>

    <hr>

    <div class="buttons">
        <input type="button" name="cancel" value="Cancel">
        <input type="button" name="confirm" value="OK">
    </div>
</div>

当前的JavaScript:(几乎是我链接问题中答案的副本)

(function () {
    nalert = window.alert;

    Type = {
        native: 'native',
        custom: 'custom'
    };
})();

(function (proxy) {
    proxy.alert = function () {
        var message = (!arguments[0]) ? 'null' : arguments[0];
        var type = (!arguments[1]) ? '' : arguments[1];

        if (type && type == 'native') {
            nalert(message);
        } else {
            // Custom alert box code
            console.log(message);
        }
    };
})(this);

理想情况下,我希望能够在// Custom alert box code部分中添加类似内容:

$('.alert.box input[name="confirm"]').on('click', function() {
    // Hide dialogue box - I can do this already

    // *** Return `true` or other truthy value from 
    // alert for use in `if()` statements
});

这样,当点击OKCancel按钮时,它会移除自定义提醒框并从调用alert() 。我已经可以使用$.fadeOut()$.remove()删除提醒,这很容易。什么不是知道如何让按钮点击事件来alert()(被覆盖)返回一些东西。

我试图尽可能地清楚,但我可能已经错过了一些东西。如果我有,请告诉我。

2 个答案:

答案 0 :(得分:4)

以下示例显示了创建自定义提醒和处理用户选择结果的方法

/*
  message = String describing the alert
  successCallBack = callback function for when the user selects yes
*/
function exampleAlert(message, successCallback)
{
    /*Alert box object*/
    var alertBox =  document.createElement("div");

    /*Alert message*/
    var msg = document.createElement("div");
    msg.innerHTML = message;

    /*Yes and no buttons
      The buttons in this example have been defined as div containers to accentuate the customisability expected by the thread starter*/
    var btnYes = document.createElement("div");
    btnYes.innerHTML= "Yes";

    /*Both yes and no buttons should destroy the alert box by default, however the yes button will additionally call the successCallback function*/
    btnYes.onclick = function(){      $(this.parentNode).remove();successCallback();}
    var btnNo = document.createElement("div");
    btnNo.innerHTML= "No"
        btnNo.onclick = function(){ $(this.parentNode).remove();}

   /*Append alert box to the current document body*/
   $(alertBox).append(msg, btnYes, btnNo).appendTo("body");
}

function test()
{
   alert("Example alert is working, don't use this test as a replacement test - horrible recursion!")  
}
exampleAlert("shoe", test)

这是相当基础的,不允许将其他数据提供给回调函数,因此不适合生产,但jQuery的.bind()和类似方法允许数据与回调方法相关联

值得评论的是,虽然上面演示了问题的全面实施,但实际上只有两行真正重要。

btnYes.onclick...
btnNo.onclick...

由于我们分别通过将onclick事件绑定为true和false来实现所需的结果,所以其他所有内容都可以绘制图片。

考虑到这一点,可以有效地将至少有一个兄弟姐妹的任何容器对象转变为一个警告框,用于简化:

   <!-- Example html -->
   <div id='a'>
      <ul>
         <ul>
            <li>Something</li>
            <li>Something Else</li>
            <li id='yesIdentifier'>Something not necessarily suggesting a trigger?</li>
         </ul>
      </ul>
   </div>  

只要您的是/否(如果不存在)选项销毁适当的容器,就可以用几行代码处理将容器转换为警告框。

$('#yesIdentifier', '#a').click(
        function(){ someCallback(); $(this).closest('#a').remove()});

以上两者都不是实施的示范模型,但应提供有关如何完成任务的一些想法。

最后......你真的需要替换原生警报方法吗?也就是说,要么你正在编写警报调用,在这种情况下你要知道使用你的自定义方法,要么你覆盖默认行为,你不能保证其他开发人员会知道。

总体建议:

我觉得最好的方法是创建一个jQuery插件,它可以动态创建自定义警报并跟踪回调,结果以及插件内的内容。

SOliver。

答案 1 :(得分:1)

为什么不直接使用这样的确认框。

var c = confirm('Confirm?');

if(c)
{
    // Yes clicked
}
else
{
    // No clicked
}

或者您可以使用jQuery UI的对话框确认框。

http://jqueryui.com/demos/dialog/#modal-confirmation