Javascript 使用jQuery检查警报的内容,然后根据内容运行函数

Javascript 使用jQuery检查警报的内容,然后根据内容运行函数,javascript,jquery,alert,Javascript,Jquery,Alert,我有一个webform,它有几个必填字段。当我提交表单时,我的CMS自动包含一些JS验证以供检查。它们的验证如下所示: function checkWholeForm88517(theForm) { var why = ""; if (theForm.CAT_Custom_1) why += isEmpty(theForm.CAT_Custom_1.value, "First Name"); if (theForm.CAT_Custom_2) why += isEmpty(th

我有一个webform,它有几个必填字段。当我提交表单时,我的CMS自动包含一些JS验证以供检查。它们的验证如下所示:

function checkWholeForm88517(theForm) {
   var why = "";
   if (theForm.CAT_Custom_1) why += isEmpty(theForm.CAT_Custom_1.value, "First Name");
   if (theForm.CAT_Custom_2) why += isEmpty(theForm.CAT_Custom_2.value, "Last Name");
   if (theForm.CAT_Custom_3) why += isEmpty(theForm.CAT_Custom_3.value, "Email Address");
   //etc.

   if (why != "") {
      alert(why);
      return false;
   }
}
当弹出警报时,它将包含如下文本:

- Please enter First Name
- Please enter Last Name
- Please enter Email Address
我想做的是运行if语句,查看警报是否包含
-请输入名字
,如果是,请执行一些操作

我试着这样做:

window.alert = function(msg) {

   if ($(this).is(':contains("- Please enter First Name")')) {
       $( ".error-msg" ).append('My Message...');
   }

}
当然,这不起作用,因为我不确定如何定位警报的
msg
,并检查它是否包含文本


我该怎么做?

您需要将参数视为字符串,而不是将上下文对象(
window
)视为DOM对象

if (msg.indexOf("some_substring") > 1)

您需要将参数视为字符串,而不是将上下文对象(
window
)视为DOM对象

if (msg.indexOf("some_substring") > 1)

在您的示例中,
可能指的是
窗口
对象。您需要测试
message
参数是否包含以下字符串:

window.alert = function(message) {
  if (/- Please enter First Name/.test(message)) {
    $(".error-msg").append(message);
  }
}
昆廷已经说过了,但我想说的是,如果您想维护或恢复原始的
.alert()
行为,可以保存对函数的引用:

var _defaultAlert = window.alert;
window.alert = function(message) {
  if (/- Please enter First Name/.test(message)) {
    $(".error-msg").append(message);
  }
  _defaultAlert.apply(window, arguments);
}

在您的示例中,
可能指的是
窗口
对象。您需要测试
message
参数是否包含以下字符串:

window.alert = function(message) {
  if (/- Please enter First Name/.test(message)) {
    $(".error-msg").append(message);
  }
}
昆廷已经说过了,但我想说的是,如果您想维护或恢复原始的
.alert()
行为,可以保存对函数的引用:

var _defaultAlert = window.alert;
window.alert = function(message) {
  if (/- Please enter First Name/.test(message)) {
    $(".error-msg").append(message);
  }
  _defaultAlert.apply(window, arguments);
}