簡體   English   中英

Javascript:onSubmit函數在函數完成之前提交表單?

[英]Javascript: onSubmit function submits form before function has finished?

我問這個是因為我自己完全失去了,需要一雙新鮮的眼睛。

在提交連接的HTML表單時成功調用以下JavaScript函數。 函數啟動並運行前兩個if語句(如果返回false ,則暫停提交)。

然后,出現第一個測試alert “之前”,然后表單提交,完全錯過了函數的其余部分。 在測試時我更改了最后一行以返回false這樣無論發生什么,函數都應返回false ,但表單仍然提交。

function validateForm(form)
{
    // declare variables linked to the form
    var _isbn = auto.isbn.value;
    var _idisplay = auto.isbn.title;
    var _iref = "1234567890X";
    // call empty string function
    if (EmptyString(_isbn,_idisplay)==false) return false;
    // call check against reference function
    if (AgainstRef(_isbn,_iref,_idisplay)==false) return false;
    // call check length function
    alert("before");///test alert

    ////// FORM SUBMITS HERE?!? /////////////

    if (AutoLength(_isbn)==false) return false;
    alert("after");///test alert
    // if all conditions have been met allow the form to be submitted
    return true;
}

編輯:這就是AutoLength樣子:

function AutoLength(_isbn) {
    if (_isbn.length == 13) {
        return true; {
    else {
        if (_isbn.length == 10) {
            return true; {
        else {
            alert("You have not entered a valid ISBN10 or ISBN13. Please correct and try again.");
            return false;
        }
    }

您的AutoLength實現中存在錯誤。 目前,它看起來像這樣:

function AutoLength(_isbn) {
    if (_isbn.length == 13) {
        return true; { // <------ incorrect brace
    else {
        if (_isbn.length == 10) {
            return true; { // <------ incorrect brace
        else {
            alert("You have not entered a valid ISBN10 or ISBN13. Please correct and try again.");
            return false;
        }
    }

看看它是如何關閉所有塊的? 那是因為你在兩個地方使用了錯誤的支架,而你卻忘了關閉這個功能。

您可以像這樣重寫函數:

function AutoLength(_isbn) {
    return _isbn.length === 13  || _isbn.length === 10;
}

如果您對使用alert感到害怕,可以在validateForm執行此操作(盡管我會嘗試找到一種更加用戶友好的方式來顯示錯誤消息)。

在將來,當您嘗試調試代碼時,可以使用trycatch來“捕獲” Errors ,如下所示:

try {
    if (false === AutoLength(_isbn)) {
        return false;
    }
} catch (e) {
    alert('AutoLength threw an error: '+e.message);
}

如果運行時錯誤終止了函數的執行,則表單提交。 因此,請查看腳本控制台日志以獲取錯誤消息。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM