2016-01-20 25 views
0

我有一個web窗體有幾個必填字段。當我提交表單時,我的CMS自動包含一些JS驗證以進行檢查。他們的驗證看起來是這樣的:檢查包含使用jQuery的警報,然後根據內容運行功能

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和檢查,看它是否包含文本。

我該怎麼做?

回答

4

您需要將參數作爲字符串處理,而不是作爲DOM對象的上下文對象(window)。

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

在你的榜樣,this可能指window對象。你需要測試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); 
} 
相關問題