2017-02-15 2 views
0

У меня проблема с моим кодом. Я толкаю элементы в новый массив и отображаю два из них в DIV. По какой-то причине он показывает один и тот же элемент дважды, а не показывает два отдельных элемента. Надеюсь, кто-то может помочь мне в этом. Мне просто нужно, чтобы один и тот же рецепт не показывался дважды в DIV.Дублирующий элемент, отображающийся в DIV

 var categoryItems = []; 
    var recipeTitle = $('#recipeTitle').text(); 

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

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

    randomRecipe = categoryItems[Math.floor(Math.random()*categoryItems.length)]; 
    for(var i = 0; i < categoryItems.length; i += 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); 
    } 

Edit: Пожалуйста, обратите внимание на эту скрипку для примера. Он не должен показывать один и тот же рецепт дважды при освежении, а показывать два разных рецепта из категории. Моя проблема заключается в том, что иногда она отображается одинаково дважды при обновлении. https://jsfiddle.net/wn4fmm5r/

+1

Пожалуйста, скрипку. Нам нужно посмотреть, что такое данные 'recipe_data' – Mojtaba

+0

Вам не хватает скобки для' if' в 'each'. Я подозреваю, что это не настоящая проблема, но исправить это. –

+0

спасибо, исправно. у меня на самом деле есть то, что в моем коде просто не копировалось за – Tom

ответ

2

вы создаете один случайный рецепт и отображение же дважды в ваш цикл

randomRecipe = categoryItems[Math.floor(Math.random()*categoryItems.length)]; 
    for(var i = 0; i < categoryItems.length; i += 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); 
    } 

попробовать, включая ваше заявление для генерации случайного рецепта внутри цикла.

 for(var i = 0; i < categoryItems.length; i += 2) { 
randomRecipe = categoryItems[Math.floor(Math.random()*categoryItems.length)]; 
     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); 
    } 

РЕДАКТИР не повторяющаяся ----

var counter; 
for (var i = 0; i < categoryItems.length; i += 2) { 
    var item = Math.floor(Math.random() * categoryItems.length); 
    if (!counter) { 
     counter = item; 
    } else { 
     if (counter == item) { 
      item = Math.floor(Math.random() * categoryItems.length); 
      counter = item; 
     } 
    } 
    randomRecipe = categoryItems[item]; 
    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); 
} 
+0

ОК это работает, но на самом деле все еще показывает дубликат после того, как пара обновляется. – Tom

+0

Это потому, что вы не можете сказать, что случайное значение не будет повторяться в вашей функции Math.Random(). – user7417866

+0

ОК, а что это за исправление? – Tom