Home  >  Q&A  >  body text

Custom Alerts: Use Javascript to customize personalized alerts

<p>How to create a custom warning function in Javascript? </p>
P粉587780103P粉587780103402 days ago568

reply all(2)I'll reply

  • P粉315680565

    P粉3156805652023-08-23 13:54:07

    This is the solution I came up with. I've written a generic function to create a jQueryUI dialog box. If you want, you can use Matt's suggestion to override the default alert function: window.alert = alert2;

    // 通用的自包含的jQueryUI替代浏览器默认的JavaScript alert方法。
    // 唯一的先决条件是包含jQuery和jQueryUI
    // 该方法自动创建/销毁容器div
    // 参数:
    //     message = 要显示的消息
    //     title = 警告框上要显示的标题
    //     buttonText = 关闭警告框的按钮上要显示的文本
    function alert2(message, title, buttonText) {
    
        buttonText = (buttonText == undefined) ? "确定" : buttonText;
        title = (title == undefined) ? "页面提示:" : title;
    
        var div = $('<div>');
        div.html(message);
        div.attr('title', title);
        div.dialog({
            autoOpen: true,
            modal: true,
            draggable: false,
            resizable: false,
            buttons: [{
                text: buttonText,
                click: function () {
                    $(this).dialog("close");
                    div.remove();
                }
            }]
        });
    }

    reply
    0
  • P粉032649413

    P粉0326494132023-08-23 12:09:20

    You can override an existing alert function that exists on the window object:

    window.alert = function (message) {
      // 对消息进行处理
    };

    reply
    0
  • Cancelreply