2017-02-15 32 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 

不像其他的答案,这也与浏览器刷新工作...