JavaScript 显示每个对象的属性(充当 foreach)


javascript display attributes from each object (act as foreach)

我从一个方法返回了一个结果(它收集了多个对象),我正在尝试显示每个对象的属性(以及某些属性)...但它只显示通知列表中的最后一个对象。

下面是我的脚本:

<script>
$(document).ready(function() {
    $('.dropdown-toggle').on('click', function() {
        // Add loading state
        $('.menu').html('Loading notifications ...');
        // Set request
        var id = "{{ Auth::user()->id }}";
        var request = $.get('/notifications/' + id);
        // When it's done
        request.done(function(response) {
            console.log(response);
            for(var index in response) {
               if (response.hasOwnProperty(index)) {
                   var attr = response[index];
                   $('.notification-list').html(attr.action + ' By: ' + attr.added_by + ' : ' + attr.created_at)
                 }
            }
        });
    });
});
</script>

我认为您每次都在输入新值。试试这个:

<script>
$(document).ready(function() {
    $('.dropdown-toggle').on('click', function() {
        // Add loading state
        $('.menu').html('Loading notifications ...');
        // Set request
        var id = "{{ Auth::user()->id }}";
        var request = $.get('/notifications/' + id);
        // When it's done
        request.done(function(response) {
            console.log(response);
            for(var index in response) {
               if (response.hasOwnProperty(index)) {
                   var attr = response[index];
                   $('.notification-list').append(attr.action + ' By: ' + attr.added_by + ' : ' + attr.created_at)
                 }
            }
        });
    });
});
</script>