2012-11-30 60 views
0

我想用其他一些Javascript函數運行jQuery函數。我想我沒有正確理解語法。我有一個在頁面加載時使用表單打開的colorbox。當提交表單時,我試圖首先進行驗證運行,然後如果成功運行關閉了Colorbox並驗證父窗口的jQuery函數。這就是我現在所在的位置(順便說一句,我已經圍繞着這個圈子,我已經能夠使jQuery函數工作,我已經獲得了驗證函數的工作,但我已經。從來沒有得到他們一起工作我很抱歉,如果我已經得到大錯特錯,但我想我已經漸行漸遠,因爲我嘗試一些新的東西):jQuery函數和Javascript函數不能一起工作

只是嘗試這樣做:

window.echeck(str) = function { 

    var at="@" 
    var dot="." 
    var lat=str.indexOf(at) 
    var lstr=str.length 
    var ldot=str.indexOf(dot) 
    if (str.indexOf(at)==-1){ 
     alert("Invalid E-mail ID") 
     return false 
    } 

    if (str.indexOf(at)==-1 || str.indexOf(at)==0 || str.indexOf(at)==lstr){ 
     alert("Invalid E-mail ID") 
     return false 
    } 

    if (str.indexOf(dot)==-1 || str.indexOf(dot)==0 || str.indexOf(dot)==lstr){ 
     alert("Invalid E-mail ID") 
     return false 
    } 

    if (str.indexOf(at,(lat+1))!=-1){ 
     alert("Invalid E-mail ID") 
     return false 
    } 

    if (str.substring(lat-1,lat)==dot || str.substring(lat+1,lat+2)==dot){ 
     alert("Invalid E-mail ID") 
     return false 
    } 

    if (str.indexOf(dot,(lat+2))==-1){ 
     alert("Invalid E-mail ID") 
     return false 
    } 

    if (str.indexOf(" ")!=-1){ 
     alert("Invalid E-mail ID") 
     return false 
    } 

    return true      
} 

window.ValidateForm() = function{ 
var emailID=document.MailingList.emailaddress 

if ((emailID.value==null)||(emailID.value=="")){ 
    alert("Please Enter your Email ID") 
    emailID.focus() 
    return false 
} 
if (echeck(emailID.value)==false){ 
    emailID.value="" 
    emailID.focus() 
    return false 
} 
return true 
} 

$(document).ready(function() { 
    $('#submitbutton').live('click', function(e) {  
     ValidateForm(); 
     parent.$.fn.colorbox.close(); 
     parent.location.href = "/SearchResults.asp?Cat=1854"; 
    }); 
}); 

我沒有執行任何功能。

當我刪除ValidateForm();從jQuery,當我把JavaScript函數的語法回function ValidateForm();而不是window.ValidateForm = function() jQuery的工作原理,但當然其他JavaScript功能不。

+0

你問什麼不,但是你的電子郵件驗證測試條件'str.indexOf(at)== lstr'沒有做你的想法,因爲'lstr'是'str.length',並且字符串的長度比最後一個索引長字符(因爲索引是從零開始的)。如果你想測試你需要的'str.indexOf(at)== lstr-1'的最後一個字符。但是我建議你用單行正則表達式'.test()'來替換測試電子郵件格式的半打if語句。 – nnnnnn

回答

1

的我不是主要的jQuery函數

不能從$(document).ready(function() { });塊外引用函數內部創建嵌套函數,因爲它是一個私人的範圍。您需要定義任意範圍之外的功能之一,因此它的訪問 -

$(document).ready(function() { 

    // define in the global scope (window) so that it's accessible anywhere 
    window.ValidateForm = function() { ... } 
}); 

// this works 
ValidateForm(); 

或導線起來使用on您的活動 -

$(document).ready(function() { 
    $("#theform").on("submit", ValidateForm); 
}); 
+0

_「因爲它是封閉的。」_ - 你在混合「封閉」和「範圍」。 – nnnnnn

+0

@nnnnnn嗯,我想我是。希望這會更好。 – McGarnagle

+0

如果我的範圍之外定義的函數(我有點明白,一個比另一個更好),我會那麼只需要調用它像一個正常的功能,即ValidateForm();如果我想用你的上面的例子? – MillerMedia

相關問題