使用选定列表项索引对JSON对象执行jQuery Grep
我有一个无序列表,包含从JSON对象创建的列表项。JSON对象中的每个项都有一个索引属性 jQuery单击绑定到UL的事件:使用选定列表项索引对JSON对象执行jQuery Grep,jquery,json,html-lists,Jquery,Json,Html Lists,我有一个无序列表,包含从JSON对象创建的列表项。JSON对象中的每个项都有一个索引属性 jQuery单击绑定到UL的事件: $j("#courseGallery li").bind('click', function () { var index = $j("#courseGallery li").index(this); GetSelectedCourseInfo(index); }); jQuery函数根据UL中选定的列表项索引过滤JSON数据: GetSelectedCou
$j("#courseGallery li").bind('click', function () {
var index = $j("#courseGallery li").index(this);
GetSelectedCourseInfo(index);
});
jQuery函数根据UL中选定的列表项索引过滤JSON数据:
GetSelectedCourseInfo = function (index) {
filteredData = $j.grep(sortedCourseData, function (e) {
return e[index] === index;
});
if ($j("#altriaCourseDetails").children().length > 0) {
$j(this).children().remove();
}
$j("#altriaCourseDetails").html($j("#selectedCourseTemplate").render(filteredData));
};
JSON数据示例:
[
{
"index":0,
"title":"Foo1",
"description":"Bar1",
},
{
"index":1,
"title":"Foo2",
"description":"Bar2",
},
{
"index":2,
"title":"Foo3",
"description":"Bar3",
}
]
很遗憾,根据索引找不到数组中的项。任何帮助都将不胜感激
谢谢。
每当你遇到这样的问题时,在你遇到这个问题的地方放一个断点。在这种情况下,它将是
GetSelectedCourseInfo = function (index) {
filteredData = $j.grep(sortedCourseData, function (e) { //breakpoint here
return e[index] === index;
});
这样,您就可以检查索引和排序数据的值。一旦达到断点,您还可以在开发工具的控制台中进行比较 您在筛选函数中犯了一个错误 应该是
return e.index === index
因为您访问的是对象而不是数组;)
fiddle:ccI使用标题解决了问题
$j("#courseGallery li").bind('click', function () {
var title = $j(this).children("#courseItemTitle").children("span").text();
GetSelectedCourseInfo(title);
});
GetSelectedCourseInfo = function (title) {
filteredData = $j.grep(sortedCourseData, function (e) {
return e.title === title;
});
if ($j("#altriaCourseDetails").children().length > 0) {
$j(this).children().remove();
}
$j("#altriaCourseDetails").html($j("#selectedCourseTemplate").render(filteredData));
};
我忘了提到我以前有过这样的代码。问题在于,从所选li返回的索引与JSON对象的索引值不匹配。因此,即使选择了第四个li(索引是3,第四个值对是从JSON中选择的,但是它的值索引是8。似乎e.index反映了JSON对象中的项目位置。