有人可以帮我解决这个问题吗?我需要做的就是防止重复显示。我正在填充一个数组并随机生成食谱。当您刷新页面时,有时同一项目会出现两次。我需要阻止这种情况发生。我在底部添加了一个 fiddle ,谢谢。
下面是我的代码:
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);
}
这是一个 fiddle :https://jsfiddle.net/wn4fmm5r/
最佳答案
选择随机项目后,只需将其从数组中删除,这样就不会再次选择它:
var randomIndex = Math.floor(Math.random()*categoryItems.length);
randomRecipe = categoryItems[randomIndex];
categoryItems.splice(randomIndex, 1);
更新的 fiddle :https://jsfiddle.net/bLpqvs4f
关于javascript - 尝试防止 DIV 中出现重复的随机项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42256422/