Jquery 循环一次或在数据数组中显示一次数据


Jquery loop once or show data once in array of data

我正在使用$.get()请求从Laravel控制器获取数据并在Javascript中获取数据数组。

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() 方法,我只需要循环一次。我得到值.价格多次,具体取决于循环长度。对于第一个 $.each,我需要一个循环,因为我有选择输入字段。有没有另一种方法代替 $.each 循环一次数据变量?我是新手,以前没有真正编写过Jquery或Javascript。

好吧,

你可以像data.spots[0].event_time这样获取data.spots中的第一个对象,然后你根本不需要循环。

不太推荐,您可以在循环的末尾放置一个return false;,例如:

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

这会立即停止循环。