2016-02-27 57 views
1

我正在使用JQuery .each()來獲取名爲「required」的類的所有值。如果這些輸入中的任何一個都是空的,我想要彈出一條警報消息。這一切都很好。但是,我對我對警報產生影響的方式並不滿意。我想使用delay()然後slideUp。但是,在使用delay()時,我會爲每個傳遞的每一個傳遞一個警報消息。使用警報時我只想要1個警報。我嘗試使用appendTo(),但沒有奏效。如何在使用.each()時多次添加警報消息

我在做什麼錯?

$(document).ready(function() { 

    $("#quotation.btn").mousedown(function() {  // THIS IS THE SUBMIT BUTTON OMN THE FORM 

     $(".required").each(function() {  //HERE IS THE EACH 

      var required = $(this).val(); // WE GRAB THE VALUES OF THE "REQUIRED FIELDS" 

      if (required == "") {     // IF ANY OF THE REQUIRED FIELDS ARE EMPTY WE EXECUTE THE FOLLOWING: 

       var message = '<p class="alert alert-danger" > You have Missed Off One or More Required Fields !</p>' 

       $("#collapseOne").collapse('show'); 
       $("#collapseThree").collapse('hide'); 

       // message.appendTo($("#alertMessage")).delay(5000).slideUp(500); // THIS DOES NOT WORK ! 

       $("#alertMessage").append(message).slideUp(10000); // THIS DOES WORK SO LONG AS I DO NOT USE DELAY() ! 

       $(this).css({"border": "solid 2px", "color": "#ff6666"}) 


      } 

      else { 
       $(this).css({"border": "1px solid #ccc", "background-image": "none"}) 

      } 
     }) 
    }); 

}); 

回答

3

你可以簡單地設置一個變量的條件語句中:

if (required == "") { 
    showAlert = true; 
} 

接外each語句,你可以檢查是否需要顯示警報:

if (showAlert) { 
    $("#alertMessage").append(message).slideUp(10000); 
    showAlert = false; 
} 
+0

謝謝非常 。我是JS新手。這很好! – Vince

+0

您可能希望將$ .trim()的值與「」進行比較。 – DinoMyte

+0

應該在事件處理程序之前聲明'showAlert',在$(「#alertMessage」)之後設置爲'false'。append(message).slideUp(10000);'被調用? – guest271314