2010-01-21 50 views
2

我有以下功能:如何停止運行在JavaScript,jQuery的功能?

function checkEmails(newEmail){ 
    $('table td:nth-child(3)').each(function(){ 
     if ($(this).html() == newEmail) 
     { 
      alert('The email address "' + newEmail + '" is already in the list. Duplicates are not allowed.'); 
      toggleSpinner(); 
      return false; 
     }   
    }); 
    return true; 
} 

我打電話就這樣在我的表單提交處理程序:

if (!checkEmails($('input#email', $('#newForm')).val())) { 
    return false; 
}//I submit the form via ajax next.... 

我只是檢查,以確保該電子郵件地址的用戶的嘗試提交不在表格中。它似乎工作得很好,除了在Firefox中,它實際上並沒有停止發生ajax請求。警告框出現,告訴我用戶已經在列表中,但是在點擊確定後,表單仍然被提交。它在IE中符合我的要求。

我在這裏做錯了什麼?

回答

5

它可能應該是這樣做的:

function checkEmails(newEmail){ 
    var ret = true; 
    $('table td:nth-child(3)').each(function(){ 
     if ($(this).html() == newEmail) 
     { 
      alert('The email address "' + newEmail + '" is already in the list. Duplicates are not allowed.'); 
      toggleSpinner(); 
      ret = false; 
     }   
    }); 
    return ret; 
} 

它在做什麼做各的元素,之前的返回值設置爲true,那麼如果發現任何無效的電子郵件地址,將其設置爲false。這是將從函數返回的值。

2

返回false是瓶蓋內,因此不會擺脫外部函數

即它返回嵌套函數虛假和不checkEmails

1

我想你想這(使用bigFatGlobal存儲返回值):

function checkEmails(newEmail){ 
    var bigFatGlobal = true; 

    $('table td:nth-child(3)').each(function(){ 
     if ($(this).html() == newEmail) 
     { 
      alert('The email address "' + newEmail + '" is already in the list. Duplicates are not allowed.'); 
      toggleSpinner(); 
      bigFatGlobal = false; 
     }   
    }); 
    return bigFatGlobal; 
} 
+3

那不是真正的全球性是什麼呢? – PeanutPower 2010-01-21 21:31:25

+0

好吧,它不是由jQuery調用的函數的本地。 – Hogan 2010-01-21 21:51:25