使用 Javascript 自定义警报

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3391864/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 04:25:48  来源:igfitidea点击:

Custom alert using Javascript

javascript

提问by Elliot Bonneville

How can I create a custom alert function in Javascript?

如何在 Javascript 中创建自定义警报功能?

回答by Matt

You can override the existing alertfunction, which exists on the windowobject:

您可以覆盖对象alert上存在的现有函数window

window.alert = function (message) {
  // Do something with message
};

回答by Walter Stabosz

This is the solution I came up with. I wrote a generic function to create a jQueryUI dialog. If you wanted, you could override the default alert function using Matt's suggestion: window.alert = alert2;

这是我想出的解决方案。我编写了一个通用函数来创建一个 jQueryUI 对话框。如果需要,您可以使用 Matt 的建议覆盖默认警报功能:window.alert = alert2;

// Generic self-contained jQueryUI alternative to
// the browser's default JavaScript alert method.
// The only prerequisite is to include jQuery & jQueryUI
// This method automatically creates/destroys the container div
// params:
//     message = message to display
//     title = the title to display on the alert
//     buttonText = the text to display on the button which closes the alert
function alert2(message, title, buttonText) {

    buttonText = (buttonText == undefined) ? "Ok" : buttonText;
    title = (title == undefined) ? "The page says:" : 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();
            }
        }]
    });
}

回答by Cristian Sanchez

Technically you can change what the alert function does. But, you cannot change the title or other behavior of the modal window launched by the native alert function (besides the text/content).

从技术上讲,您可以更改警报功能的作用。但是,您不能更改由本机警报功能启动的模态窗口的标题或其他行为(除了文本/内容)。

回答by advait

If you're looking for a javascript/html/css replacement, I recommend checking out jQueryUIand its implementation of modal dialogs.

如果您正在寻找 javascript/html/css 替代品,我建议您查看jQueryUI及其对模态对话框的实现。

回答by dabeng

"override" way is not good enough, suggest you to create a custom popup box. The best benefit of this solution is that you can control every details.

“覆盖”方式不够好,建议您创建一个自定义弹出框。此解决方案的最大好处是您可以控制每一个细节。