【问题标题】:Override alert box when contains specific string包含特定字符串时覆盖警报框
【发布时间】:2014-10-27 16:33:22
【问题描述】:

当警报框包含特定字符串时,我想覆盖它的样式,否则保留为默认值。我尝试通过控制台记录它,以便我可以输入 if 条件,但响应采用以下方式:

function alert() { [native code] }

当我尝试了以下不同的东西时:

window.old_alert = window.alert;
window.alert = function(message){
  console.log(message);
  alert(message);
}

我在控制台中收到警报消息,但由于未知原因,我的浏览器冻结了 1000 多次,并且窗口中没有任何弹出窗口。这应该如何处理?任何帮助或指导都非常受欢迎。

【问题讨论】:

    标签: javascript jquery overriding alert


    【解决方案1】:
    window.old_alert = window.alert;
    window.alert = function(message){
      console.log(message);
      alert(message); //THIS called the new alert recursively, hence the freeze
    }
    

    你想做的是:

    window.oldAlert = window.alert;
    window.alert = function(message) {
        var SpecificString="test";
        if(message.indexOf(SpecificString) >= 0) {
            console.log(message);
        } else {
            window.oldAlert(message);
        }
    }
    

    Here's a jsfiddle

    【讨论】:

    • 非常感谢您的指导。 :)
    【解决方案2】:

    您刚刚使用该代码导致了无限递归!

    window.old_alert = window.alert;
    window.alert = function(message){
        console.log(message);
        alert(message); // this calls your modified alert causing an infinite recursion
    }
    

    你需要的是:

    window.old_alert = window.alert;
    window.alert = function(message){
        if(message === "some special string") my_new_alert(message); // call special alert
        else old_alert(message); // this calls the original alert
    }
    ..
    my_new_alert = function(message) {
        // modified alert UI
    }
    

    【讨论】:

      【解决方案3】:

      您可以像这样覆盖alert,但不能更改警告框的默认样式。如果您需要不同样式的警报,则需要使用自己的弹出对话框。

        var old_alert = window.alert;
      
        window.alert = function() {
          console.log(arguments[0]);
          return old_alert.apply(this, arguments);
        };
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-04-21
        • 2010-12-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-06-20
        • 1970-01-01
        • 2021-12-10
        相关资源
        最近更新 更多