jQuery触发器-只返回一个对象,而不是JSON提取的所有对象

jQuery Trigger - returning only a single object and not all objects fetched by JSON

本文关键字:提取 JSON 对象 -只 触发器 返回 一个对象 jQuery      更新时间:2023-09-26

所以我正在学习jQuery,并且创建了一个在检索JSON数据时执行的触发事件。我想提取所有的对象,但无法这样做。我认为这是由于JSON对象的检索方式造成的。

这是我正在使用的一个代码。

<script>
$.getJSON('http://jsonplaceholder.typicode.com/users', function( results ){
    console.log(results) // prints the correct value. All the objects
    $(document).trigger('jph/photos', results);
}); 
$(document).on('jph/photos', function(e, results ){
    console.log( results ) // returns a single object??
    $('ul.tweets').html(
        $.map(results, function(obj, index){
            return '<li>'+obj.name+'</li>';
        })
    );  
});
</script>

我认为问题是,如果它是一个数组,那么额外的params值将被展平,这意味着如果您将数组作为第二个参数传递,那么数组中的每个对象都将作为一个单独的参数传递给回调。

即,如果您传递一个包含3个项的数组,回调将总共接收4个参数,如function(event, item1, item2, item3){}而不是function(event, arrayof3items){}

对此的一个解决方案是用另一个数组包装您的数组,这样当包装数组被展平时,它将获得原始数组,并将其作为参数传递给类似的回调

$.getJSON('http://jsonplaceholder.typicode.com/users', function (results) {
    console.log(results) // prints the correct value. All the objects
    $(document).trigger('jph/photos', [results]);
});

尝试将参数设置为.trigger作为对象数组,在事件处理程序中使用Array.prototype.slice

var data = [{
  "name": 123
}, {
  "name": 456
}];
$(document).on("jph/photos", function(e) {
  // slice arguments starting at index 1
  var results = Array.prototype.slice.call(arguments, 1);
  $("ul.tweets").html(
    $.map(results, function(obj, index) {
      return '<li>' + obj.name + '</li>';
    })
  );
});
$(document).trigger("jph/photos", data);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
<ul class="tweets"></ul>