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

Check contains of an alert using jQuery, then run function based on contents

我有一个包含多个必填字段的网络表单。当我提交表单时,我的 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 语句,以查看警报是否包含 - Please enter First Name,如果包含,则执行一些操作。

我试过这样做:

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)

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

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

Quentin 已经说过了,但我想提一下,如果你想保持或恢复原来的 .alert() 行为,你可以保存对函数的引用:

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