Javascript 按类别对JSON内容排序

Javascript 按类别对JSON内容排序,javascript,jquery,html,json,sorting,Javascript,Jquery,Html,Json,Sorting,我有一个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,

我有一个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>

功能类别(类型)
{
$.getJSON('products.json',函数(数据){
$(“.products”).empty();
$(数据.产品.类型).每个(功能(索引,项目){
if(Genre==this.Genre){
$(“”,{class':'productname',文本:item.Name})。追加(
$(“”,{class':'productdetails',文本:'Album:'+item.Album}),
$('',{'class':'productdetails'}).append($('',{'class':'productdetails',text:'Genre:'+item.Genre}),
$(“”,{class':'productdetails',text:'Price:'+item.Price}),
$(“”,{class':'productdetails',text:'Quantity:'+item.Quantity}),
$(“”,{class':'productdetails',text:'Tracks:'+item.Tracks}),
$('')。追加(
$('',{'class':'productbutton'})
.text('添加到购物车')
。单击(函数(){
$.fn.SaveToCart(i,item.Name,item.Album,item.Price);
})
)
).附于(“产品”);
}
});
});
}
HTML:


类别
  • 摇滚乐
  • 电的
  • 嘻哈
  • 环境的
  • 电子
  • 未来车库





当我点击一个链接时,什么都没有发生。

修复了javascript代码中的一些错误:

1) 您正在遍历每个产品,因此出现了
$(data.Products).每个(function..

2)
if(Genre==item.Genre){

试一试:

<script>

        function Categories(Genre)
        {
            $.getJSON('products.json', function(data) {
                $(".products").empty();
                $(data.Products).each(function(index, item){
                if(Genre == item.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>

功能类别(类型)
{
$.getJSON('products.json',函数(数据){
$(“.products”).empty();
$(data.Products).每个(函数(索引,项){
如果(类型==项目类型){
$(“”,{class':'productname',文本:item.Name})。追加(
$(“”,{class':'productdetails',文本:'Album:'+item.Album}),
$('',{'class':'productdetails'}).append($('',{'class':'productdetails',text:'Genre:'+item.Genre}),
$(“”,{class':'productdetails',text:'Price:'+item.Price}),
$(“”,{class':'productdetails',text:'Quantity:'+item.Quantity}),
$(“”,{class':'productdetails',text:'Tracks:'+item.Tracks}),
$('')。追加(
$('',{'class':'productbutton'})
.text('添加到购物车')
。单击(函数(){
$.fn.SaveToCart(i,item.Name,item.Album,item.Price);
})
)
).附于(“产品”);
}
});
});
}

此处更正了一些错误:

  • 循环使用data.Products而不是data.Products.Genre

  • 与项目进行比较,而不是与此项目进行比较

  • 附加到.products,而不是不存在的#products, 根据你的HTML

不要忘记用你的东西中的数据替换JSON,以及我不能在JSFIDLE中使用的$.getJSON调用! 并删除窗口。类别,只需将类别放置在全局范围内

小提琴:

HTML:


类别
  • 摇滚乐
  • 电的
  • 嘻哈
  • 环境的
  • 电子
  • 未来车库




当然,我使用的是静态JSON变量

JS:

var JSON={
“产品”:[
{“姓名”:“平克·弗洛伊德”,
“专辑”:“平克·弗洛伊德的最佳作品:一只脚在门上”,
“标签”:“EMI英国”,
“曲目”:“嘿,你,看艾米丽的表演,我们一生中最快乐的日子,墙上的另一块砖头(第二部分),抽支雪茄,祝你在这里,时间,天空中的伟大演出,金钱,舒适的麻木,满怀希望,学飞,弗莱彻纪念馆,闪耀你疯狂的钻石,脑损伤,月蚀”,
“价格”:“16.40”,
“流派”:“摇滚”,
“来源”:http://upload.wikimedia.org/wikipedia/en/thumb/3/38/AFootInTheDoorPinkFloyd.jpg/220px-AFootInTheDoorPinkFloyd.jpg",
“数量”:10
},
{
“名称”:“Depeche模式”,
“专辑”:“时间的问题”,
“标签”:“静音”,
“曲目”:“时间问题,黑人庆典,要做的事,脱光衣服,不仅仅是派对,时间问题(延长),黑人庆典”,
“价格”:“4.68”,
“流派”:“摇滚”,
“来源”:http://dmremix.be/images/AQuestionOfTime.jpg",
“数量”:10
}
]
}
//窗口仅用于JSFIDLE,因为我在jQuery范围内。
window.Categories=函数(类型){
$(“.products”).empty();
//在JSON.Products上循环
$(JSON.Products)。每个(函数(索引,项){
//与项目进行比较,而不是与此项目进行比较
如果(类型==项目类型){
$(“”,{class':'productname'}).text(item.Name).append(
$(“”,{class':'productdetails',文本:'Album:'+item.Album}),
<script>

        function Categories(Genre)
        {
            $.getJSON('products.json', function(data) {
                $(".products").empty();
                $(data.Products).each(function(index, item){
                if(Genre == item.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>
<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>
var 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
        }
    ]
}

// window is JUST for the JSFiddle cause I'm in a jQuery scope.
window.Categories = function (Genre) {
    $(".products").empty();
    // Loop on JSON.Products
    $(JSON.Products).each(function(index, item) {
        // Compare to item instead of this
        if(Genre == item.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"); // .products instead of #products cause you're using a class
        }
    });
};
var obj={
    "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
        }
    ]
}

keys=["Genre","Name"];//Sorts by Genre then Name
obj.Products.sort(function(a,b){
  var ret=0,i=0;
  while(ret==0&&i<keys.length){
      ret=(a[keys[i]]>b[keys[i]])?1
        :(a[keys[i]]<b[keys[i]])?-1:0;
      i++;
   }
   return ret;
});
console.log(obj.Products)