任何人都可以幫助我嗎?我需要做的就是防止重複顯示。我正在填充一個數組並隨機生成食譜。刷新頁面時,有時相同的項目會出現兩次。我需要防止這種情況發生。我在底部包括一個小提琴謝謝。試圖阻止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/
的偉大工程!謝謝! – Tom