只想使用返回值并忽略警报

Only want to use the return value and ignore the alert

本文关键字:返回值 只想      更新时间:2023-09-26

我想创建一个函数,它将使用下面粘贴的多个函数。我想忽略警报,只使用返回值,这可能吗?感谢

function ageFormatAll()
{
   var age = document.getElementById('ageGrade').value;
   var patt=/^(?:'d{2}'.'d{2}|)$/;
   if (! patt.test(age) )
   {
    alert("Value entered doesn't match the correct format");
    return "Age grade doesn't match format.'n";
   } else 
   { return "" };
}

当然不能。只需从功能中删除警报。

但是有一种垃圾和不可靠的方法可以实现你想要的:

// remember alert to restore later
var alert_ = alert;
// override alert with an empty function
alert = function() {};
// get the result
var result = ageFormatAll();
// restore the alert function
alert = alert_;

但不要这样使用:这是一件很好的事情,知道但不要使用。

是否删除警报?或者,如果要有条件地显示警报,请修改函数。将if检查作为参数。这样,您就可以在其他场景中原样重新使用它,并且只需在不需要警报时传递一个参数。

function ageFormatAll(doNotShowAlert)
{
   var age = document.getElementById('ageGrade').value;
   var patt=/^(?:'d{2}'.'d{2}|)$/;
   if (! patt.test(age) )
   {
    if(doNotShowAlert !== undefined && doNotShowAlert) {
    alert("Value entered doesn't match the correct format");
    }
    return "Age grade doesn't match format.'n";
   } else 
   { return "" };
}