function loadResponse(filter) {
$.ajax({
type: 'GET',
url: 'path/to/example.json',
dataType: 'json',
cache: false,
beforeSend: function () {
console.log('loading');
},
success: function (response) {
//console.log('success, filtering response..');
var filtered = $(response).filter(function (i, n) {
return n.type === filter; //not working
});
console.log('filter by json ' + filtered);
for (var key in filtered) {
if (filtered.hasOwnProperty(key)) {
console.log('list ' + filtered[key]["description"]);
console.log('list ' + filtered[key]["name"]);
}
}
}
});
}
console.log
一直在为undefined
提供说明或名称。但是我没有测试过:
var filtered = $(response).filter(function (i,n) {
return n.type === filter; //not working
});
能够在console.log
中获取说明和姓名。好像$(response).filter
似乎没有返回任何东西。不知道哪里出错了。
更新
请参阅JSON - 响应应打印出名称和类型。所以需要在json里面过滤类型
[
{
"name": "Jonathan Suh",
"type": "zoologist, hobbyist"
},
{
"name": "William Philbin",
"type": "judge, hobbyist"
},
{
"name": "Allison McKinnery",
"type": "hobbyist"
}
];
$('.filter a').on('click', function(e){
e.preventDefault();
loadResponse($(this).attr('id'));
});
示例:
<a href='#' id="hobbyist">Hobbyist</a>
所以点击上面的内容,它应该给我3个爱好者的名单。
答案 0 :(得分:1)
根据API过滤器:
将匹配的元素的集合减少为与选择器匹配的 或传递函数的测试。
(强调我的)
我认为它适用于DOM元素而不是JSON对象
您可以尝试使用jquery.grep()
<强>已更新强>
使用grep()
的示例 - &gt;点击
$(function() {
var arr = [{
"name": "Jonathan Suh",
"type": "zoologist, hobbyist"
}, {
"name": "William Philbin",
"type": "judge, hobbyist"
}, {
"name": "Allison McKinnery",
"type": "hobbyist"
}];
var doFilter = function(arr, filterParam) {
return jQuery.grep(arr, function(n, i) {
console.log(n.type.indexOf(filterParam));
return (n.type.indexOf(filterParam) > -1);
});
};
$(".filter").on('click', function() {
var filterName = $(this).attr('id');
console.log(filterName);
if (filterName) {
var filteredResults = doFilter(arr, filterName);
console.log(filteredResults);
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h3>See console for outputs when clicking</h3>
<a href='#' class="filter" id="hobbyist">Hobbyist</a>
<br/>
<a href='#' class="filter" id="judge">Judge</a>