2017-04-03 42 views
0

我有以下javascript/jquery代碼。如何在滿足某些條件時退出jQuery .on()函數中的函數

我是一個JavaScript新手,所以我很抱歉如果這個問題是非常容易解決的。 如果出現錯誤或服務器上沒有找到密鑰,我想退出此.on('click')功能。這點擊綁定會在表單上觸發一個發佈請求,所以如果這兩個條件都不符合,我想繼續運行它。我查了其他例子,我嘗試了很多東西,例如return,.stopPropagation等。

我應該怎麼做?我嘗試了return;return false;,但它仍然刷新頁面並觸發表單上的發佈請求。

我在做什麼錯?

$(document).ready(function() { 

    var validation = false; 
    $('#submitform').on('click', function(e) { 

     if (validation === true) { 
      validation = false; // reset flag 
      return;// let the event bubble away 
     } 

     if ($('#street_number') == "" && $('#route') == "" && $('#lat') == "" && $('#lon') == "" 
       && $('#administrative_area_level_1') == "") { 
      alert("Unknown Address"); 
      validation = false; 
      e.preventDefault(); 
      return false; 
     } 
     else { 
      var data_dict = { 
       // Number 
       'street_number': $('#street_number').val(), 
       // Address 
       'address': $('#route').val(), 
       // City 
       'city': $('#locality').val(), 
       // postal code 
       'postal_code': $('#postal_code').val(), 
       // State 
       'state': $('#administrative_area_level_1').val(), 
       // Country 
       'country': $('#country').val() 
      }; 
      $.ajax({ 
       url: '/zillow_check/', 
       data: data_dict, 
       method: 'POST' 
      }).then(function (response) { 
       console.log("Checking for Zillow ID..."); 
       if (response.error) { 
        console.error("There was an error " + response.error); 
        $('.dashboard-main__appartment--input').addClass('serverError'); 
        validation = false; 
        e.stopImmediatePropagation(); 
        return; 
       } else { 
        console.log("Zillow key: " + response); 
        if (response == 'No zillow ID found.') { 
         // You can change this to whatever you like. 
         alert("Can't add this object. It does not exist on Zillow. Check the Address and try again."); 
         validation = false; 
         e.stopImmediatePropagation(); 
         return; 

        } 
        else if (isNaN(response) == false) { 
         validation = true; 
         $('#propertyform').submit() 
        } 
       } 

      }); 

     } 
    }); 
}); 

回答

1

您需要立即阻止所有案例的默認設置。

Ajax是異步的,所以你不能等待它完成嘗試阻止默認值,那麼......已經太晚了。

$('#submitform').on('click', function(e) { 
    e.preventDefault(); 
    // no need for other instances of preventDefault() beyond here or for `stopImmediatePropagation()` 

    // your other code 

}) 
+0

我試過這種解決方案。不幸的是,在我把'''e.preventDefault();'''放在你建議的地方後,它不會提交表單。我需要以不同方式處理該案件嗎? –

+0

你正在用'$('#propertyform')。submit()'在ajax成功回調中提交它。如果這不起作用,那麼你需要調試其他條件 – charlietfl

+0

我已經將console.log語句添加到該塊,並且它正確地觸發該語句,但它不提交表單。如果我刪除'''e.preventDefault()'''它可以工作,但在這種情況下的其他條件仍然提交表單,這使我們回到原來的問題。 –

相關問題