2016-04-27 50 views
2

我正在使用$ .get()請求從Laravel控制器中獲取數據並獲取Javascript中的數據數組。jquery循環一次或在數據數組中顯示一次數據

function getSpots1(){ 

var spots = $('#event-spots1'); 
    spots.empty(); 
    spots.html('<p><i class="uk-icon-refresh uk-icon-medium uk-icon-spin"></i></p>'); 
    var event_id = $("#event-event_id").val(); 
    var event_date = $("#event-date").val(); 
    var code = ''; 
    console.log(event_date); 
    $.get("/1/users/spots/" + event_id + "/" + event_date + "/date", function(data) { 
     spots.empty(); 
     console.log(data); 

     code += '<label for="event_time" class="uk-form-label">Select Time</label><select class="uk-width-1-1" name="event_time" id="event-time">'; 
     $.each(data.spots, function(index, value) 
     { 
      code += '<option value="' + value.event_time + '">' + value.event_time + '</option>'; 
     }); 

     code += '</select><p class="uk-form-help-block uk-text-muted">The spot you\'re booking</p>'; 
     code += '</br><div class="uk-margin-bottom"><label for="event_time" class="uk-form-label">Price</label>'; 

     $.each(data.spots, function(index, value) 
     { 
      code += '<input type="text" class="uk-width-1-1" value="' + value.price + '" disabled />';  
     }); 

     spots.append(code); 
     getSpots2(); 
    }); 

} 

我有$ .each()jquery方法來遍歷數組數組。但對於第二個$ .each()方法,我只需要循環一次。我得到value.price多次取決於循環長度。對於第一個$。每個我需要一個循環,因爲我有選擇輸入字段。 有沒有另一種方法,而不是$ .each循環一次通過數據變量?我是新的,並沒有真正編碼Jquery或Javascript之前。

回答

3

那麼你可以得到data.spots中的第一個對象,例如data.spots[0].event_time,然後你就不必循環了。

少推薦,你可以只是把return false;在例如像一個循環的末尾:

$.each(data.spots, function(index, value) 
     { 
      code += '<input type="text" class="uk-width-1-1" value="' + value.price + '" disabled />'; 
      return false; 
     }); 

其立即停止循環。

+1

你是對的,爲什麼只有循環訪問一個對象? – rosscooper

+0

謝謝,這兩個解決方案的作品。與循環,沒有它也:) –