[英]How to stop function from running in 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中工作。
我在這做錯了什么?
應該這樣做:
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。 這是從函數返回的值。
返回false在閉包內部,因此它不會突破外部函數
即它為嵌套函數返回false而不是checkEmails
我想你想要這個(使用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;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.