jQuery触发器-只返回一个对象,而不是JSON提取的所有对象
jQuery Trigger - returning only a single object and not all objects fetched by JSON
所以我正在学习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>
相关文章:
- 如何从两个不同的来源提取JSON数据
- 如何从生成的JSON数组中提取JSON对象
- 从Node.js中的JSON数据中提取JSON字段
- 从 JSON 数组中提取 JSON 对象
- 从 html 文档中提取 json var
- 提取 JSON 对象未定义
- 从文本中提取 JSON
- 如何按条件提取 json 元素
- 如何提取 json 对象内的 json 对象
- 使用 javascript 提取 json 数组数据
- 在 Javascript 中解析和提取 JSON
- 使用 Python 从同样包含非 JSON 声明的.js文件中提取 JSON
- 如何提取json数据,并通过js为每个拆分元素追加
- 提取Json响应
- 如何在angular js中从HttpResponse中提取JSON数据
- 点击即可从json文件中提取json数据
- 只想提取JSON类而不是所有数据
- 如何使用JavaScript变量提取JSON字符串
- Angular JS提取JSON数据
- 用Javascript从HTML输入字段中提取JSON变量