覆盖警报并在 Javascript 中确认

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5560367/
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-10-25 17:37:35  来源:igfitidea点击:

Override alert and confirm in Javascript

javascriptjquery

提问by Shawn Mclean

Is there a way to override alert("")and confirm("")in javascript?

有没有办法在javascript中覆盖alert("")confirm("")

I use jQuery, so if there is a way to do it in this framework, I'd appreciate it.

我使用 jQuery,所以如果有办法在这个框架中做到这一点,我会很感激。

I'd like to do stuff like:

我想做这样的事情:

override alert(msg){
    //Show custom stuff here
}

override confirm(msg){
    //Show custom stuff here.
    return watever;
}

回答by Mark Kahn

Yes and no. You can simply replace them:

是和否。您可以简单地替换它们:

window.alert = function(msg){
    // stuff
}

but you're not going to get the blocking functionality that alert and confirm give you, i.e. there will be NO way to get this code to work:

但你不会得到警报和确认给你的阻塞功能,即没有办法让这段代码工作:

if(confirm('Do Something?')){
   // do stuff
}

You're generally better off making other functions to do similar things than you are trying to replace these.

通常最好让其他函数来做类似的事情,而不是试图替换它们。

回答by ctcherry

Just redefine it:

只需重新定义它:

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

回答by meder omuraliev

Just define a function named alertor confirm.

只需定义一个名为alertor的函数confirm

function alert(){}; function confirm(){};

However, if you need reference to the original functions then you should save references to those by assigning var oldAlertor just define alertinside of another function, so window.alertstays untouched.

但是,如果您需要对原始函数的引用,那么您应该通过分配var oldAlert或仅alert在另一个函数内部定义来保存对这些函数的引用,因此window.alert保持不变。

(function() {
  function alert(){}; // alert inside of this scope is your custom function
})();