次のような JSON ファイルのセットアップがあります。
{
"Products": [
{ "Name": "Pink Floyd",
"Album": "The Best Of Pink Floyd: A Foot In The Door",
"Label": "EMI UK",
"Tracks":"Hey You, See Emily Play, The Happiest Days Of Our Lives, Another Brick in The Wall (Part 2), Have a cigar, Wish You Where Here, Time, The Great Gig in the Sky, Money, Comfortably Numb, High Hopes, Learning to Fly, The Fletcher Memorial Home, Shine On You Crazy Diamond, Brain Damage, Eclipse" ,
"Price": "16.40",
"Genre": "Rock" ,
"Source": "http://upload.wikimedia.org/wikipedia/en/thumb/3/38/AFootInTheDoorPinkFloyd.jpg/220px-AFootInTheDoorPinkFloyd.jpg",
"Quantity": 10
},
{
"Name": "Depeche Mode",
"Album": "A Question Of Time",
"Label": "Mute",
"Tracks":"A Question Of Time, Black Celebration, Something To Do, Stripped, More Than A Party, A Question Of Time(extended), Black Celebration" ,
"Price": "4.68" ,
"Genre": "Rock",
"Source": "http://dmremix.be/images/AQuestionOfTime.jpg",
"Quantity": 10
},
..........
}
]
}
カテゴリを「ジャンル」でソートしようとしています。つまり、「ジャンル」リンクをクリックするたびに、すべての製品がテーブルから消去され、ジャンルが「x」のアイテムのみが表示されます。
これは私が試したものです:
<script>
function Categories(Genre)
{
$.getJSON('products.json', function(data) {
$(".products").empty();
$(data.Products.Genre).each(function(index, item){
if(Genre == this.Genre){
$('<div/>', {'class':'productname',text:item.Name}).append(
$('<div/>', {'class':'productdetails', text:'Album: '+item.Album}),
$('<div/>', {'class':'productdetails'}).append($('<img>').attr({src:item.Source,title:item.Name,alt:item.Name,class:'productimage'})),
$('<div/>', {'class':'productdetails', text:'Genre: '+item.Genre}),
$('<div/>', {'class':'productdetails', text:'Price: '+item.Price}),
$('<div/>', {'class':'productdetails', text:'Quantity: '+item.Quantity}),
$('<div/>', {'class':'productdetails', text:'Tracks: '+item.Tracks}),
$('<div/>').append(
$('<button />', {'class':'productbutton'})
.text('Add To Cart.')
.click(function(){
$.fn.SaveToCart(i,item.Name, item.Album, item.Price);
})
)
).appendTo("#products");
}
});
});
}
</script>
HTML:
<div class="categories">
<h2>Categories</h2>
<ul>
<li><a class="" onclick="Categories('Rock')"><span>Rock</span></a></li>
<li><a class="" onclick="Categories('Electro')"><span>Electro</span></a></li>
<li><a class="" onclick="Categories('Hip Hop')"><span>Hip Hop</span></a></li>
<li><a class="" onclick="Categories('Ambient')"><span>Ambient</span></a></li>
<li><a class="" onclick="Categories('Electronica')"><span>Electronica</span></a></li>
<li><a class="" onclick="Categories('Future Garage')"><span>Future Garage</span></a></li>
</ul>
</div> <br><br><hr><hr>
<div class="products"></div>
リンクをクリックしても何も起こりません。