有没有办法禁止警报?

我有很多用于程序的 JavaScript 函数,所有这些函数都包含alert通知用户某些事情的 s。我想让用户选择禁止所有这些警报,而不必在没有警报的情况下重写所有功能。有办法禁止alert吗?也许是这样的:


<button onclick = "alertBan()">Alert Ban</button>

function alertBan(){

     alerts = false;

}


慕斯王
浏览 82回答 2
2回答

牛魔王的故事

只需将一个空函数分配给alert.function alertBan(){&nbsp; &nbsp; &nbsp;alert = function(){};}如果您稍后可能需要重新启用警报,您可以window.alert在页面加载时存储在一个变量中。const oldAlert = alert;function alertBan(){&nbsp; &nbsp; &nbsp;alert = function(){};}function enableAlerts(){&nbsp; &nbsp; alert = oldAlert;}

四季花海

存储原始警报以备后用。通过空函数或设置参数替换警报以写入控制台。如果需要正常的警报返回,请将存储的警报取回。alertOrig = alert;function alertBan(consoleLog){&nbsp; &nbsp; alert = function(e) {&nbsp; &nbsp; &nbsp; &nbsp; if (consoleLog) console.log(e);&nbsp; &nbsp; }}function alertEnable(){&nbsp; &nbsp;if ( alertOrig )&nbsp; &nbsp; &nbsp; &nbsp;alert=alertOrig;}alertBan();alert('No console + no alert');alertBan(true);alert('With console');alertEnable();alert('Normal alert');
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript