按类别排序JSON内容

时间:2013-04-25 09:58:19

标签: 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, 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”的项目。< / p>

这就是我的尝试:

<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>

当我点击链接时,没有任何事情发生。

3 个答案:

答案 0 :(得分:2)

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

1)您正在遍历每个产品,因此$(data.Products).each(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>

答案 1 :(得分:0)

在那里纠正了一些错误:

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

  • 与项目进行比较而不是

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

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

小提琴:

http://jsfiddle.net/NA5tt/2/

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>

我当然使用静态JSON var ...

JS:

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
        }
    });
};

答案 2 :(得分:0)

以下是对数据对象进行排序的方法,只需对对象进行排序并重新创建表:

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)