2017-02-15 41 views
0

任何人都可以幫助我嗎?我需要做的就是防止重複顯示。我正在填充一個數組並隨機生成食譜。刷新頁面時,有時相同的項目會出現兩次。我需要防止這種情況發生。我在底部包括一個小提琴謝謝。試圖阻止DIV中的重複隨機項目

下面是我的代碼:

var recipe_data = [ 
    { 
     "id":"11", 
     "recipeName":"Hummus", 
     "recipeCategory":"4", 
     "recipeImageCategoryURL":"http://www.slurrpy.com/wp-content/uploads/2012/08/roasted-eggplant-hummus-800x500.jpg" 
    }, 
    { 
     "id":"12", 
     "recipeName":"Antipasto", 
     "recipeCategory":"4", 
     "recipeImageCategoryURL":"http://static.menutabapp.com/img/cache/800x500/2012/10/23/7857b394d50293d29443dc09eac76b3d.jpeg" 
    }, 
    { 
     "id":"10", 
     "recipeName":"Zucchini", 
     "recipeCategory":"4", 
     "recipeImageCategoryURL":"https://paleofood.io/wp-content/uploads/2016/05/garlic-shrimp-zucchini-noodle-main-800x500.jpg" 
    } 
] 

    var categoryItems = []; 

     $.each(recipe_data, function(i, item){ 
      if (item.recipeCategory == "4") { categoryItems.push(item); } 
     }); 

     var similarRecipe = ''; 
     var randomRecipe = {}; 


     for(var i = 0; i < categoryItems.length; i ++) { 

      randomRecipe = categoryItems[Math.floor(Math.random()*categoryItems.length)]; 
      categoryItems.length = 2; 

      similarRecipe = [ '<div class="col-md-6 col-sm-6 img-margin">' + ' <div class="addthis_inline_share_toolbox" data-url="' + randomRecipe.recipePageURL +'" data-title="' + randomRecipe.recipeName + '"></div>' 
      + '<a href="' + randomRecipe.recipePageURL +'">' + '<img class="img-responsive" src="' + randomRecipe.recipeImageCategoryURL + '">' + '</a>' 
      + '<a href="' + randomRecipe.recipePageURL +'">' + '<h3 class="recipeSubCategoryImgCaption">' + randomRecipe.recipeName + '</h3>' + '</a>' + '</div>' ]; 
      $('#recipeSimilar').append(similarRecipe); 

     } 

這裏是一個小提琴:https://jsfiddle.net/wn4fmm5r/

回答

2

選擇一個隨機項後,剛剛從數組中刪除它,所以它不會再次回升:

var randomIndex = Math.floor(Math.random()*categoryItems.length); 

randomRecipe = categoryItems[randomIndex]; 

categoryItems.splice(randomIndex, 1); 

更新提琴:https://jsfiddle.net/bLpqvs4f

+0

的偉大工程!謝謝! – Tom

1

我su ppose在這種情況下你想從recipe_datan不同的物品? 在這種情況下,你應該寫一個指定的函數得到你想要

function getRandomItems(noOfItems, source){ 
    var samples = source.slice(); 
    var results = []; 

    for(var i=0; i < noOfItems;i++){ 
     results = results.concat(samples.splice(Math.floor(Math.random() * samples.length), 1)); 
    } 

    return results; 
} 

有些東西這裏要注意的是使用.slice()到淺拷貝一個數組,而不是運行一個for循環來添加項目的項目,當你想從數組中拉項目.splice()是可供選擇的功能。

觀看演示:https://jsfiddle.net/wn4fmm5r/3/

+0

謝謝!這也適用。很棒的解決 – Tom

1

可以在最後一次配方ID存儲在本地存儲,以防止再次顯示它的(我想清爽的手段重新加載頁面?)?

var showed=localStorage.getItem("stored")||[];//get the recipes already showed 
var id; 
while(!id||showed.find(el=>el===id)){//retry until generated a new one 
    id=Math.floor(Math.random()*categoryItems.length);//generate new one 
} 
showed.push(id); 
localStorage.setItem("stored",showed);//store again 
randomRecipe = categoryItems[id];//your new & random recipe 

不像其他的答案,這也與瀏覽器刷新工作...