2016-04-27 52 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

谢谢,这两个解决方案的作品。与循环,没有它也:) –