2013-04-25 2 views
0

У меня есть настройка JSON-файл, как это:содержание Сортировка 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> 

Когда я нажимаю на ссылку, ничего не происходит.

+4

И что не так? – Sirko

+0

Разве вы не догадались? :) –

+0

Какая ошибка вы получаете? –

ответ

0

Некоторые ошибки исправлены там:

  • Петля на data.Products вместо data.Products.Genre

  • Сравнить пункт вместо этого

  • Append к .продукции вместо #products, что не существует, в соответствии с вашим HTML!

Не забудьте заменить JSON данных в ваших вещах, и $ .getJSON вызов, который я не могу использовать в JSFiddle! И удалите window.Categories, просто поместите категории в глобальную область.

Fiddle:

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 вар конечно ...

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

Пробовал свой код, но он не работает. (Это то, что я сделал: http://pastebin.com/GjftP24h) – JustAJDoe

+0

Да, вам нужно заменить .products на #products, если вы измените class = 'products' на id = 'products'! Имейте в виду, что # обозначает идентификатор и. для класса при выборе с помощью jQuery! –

+0

По какой-то причине он по-прежнему не работает. Когда я нажимаю, ничего не происходит. – JustAJDoe

2

Исправлено несколько ошибок в вашем яваскрипте кода:

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

Нет, ничего не происходит. Когда элемент кликается, страница остается такой, какая была. – JustAJDoe

+0

Я также заметил, что вы опорожняете div с помощью «продуктов» класса, а затем добавляете в div с идентификационными «продуктами». Что это? – Mysteryos

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) 
+0

Вы помещаете этот код в файл JSON? – JustAJDoe

+0

, конечно, нет! JSON - это формат данных, а не формат файла сценария! Поместите это внутри тега