1

Есть массив:

Array(3) [ "авокадо", "сыр", "угорь" ]

Есть вертска:

<div class="products">
    <div class="product">
        <span class="description">Сыр, чеснок</span>
    </div>
    <div class="product">
        <span class="description">Томат, капуста</span>
    </div>
    <div class="product">
        <span class="description">Огурец, помидор</span>
    </div>
    <div class="product">
        <span class="description">авокадо, помидор</span>
    </div>
</div>

Подскажите, пожалуйста, как получить все элементы product , в которых присутсвуеют элементы массива, в данном случае нужно получить:

<div class="product">
        <span class="description">Сыр, чеснок</span>
    </div>
<div class="product">
        <span class="description">авокадо, помидор</span>
    </div>

Полный листинг фильтра:

<script type="text/javascript">
    var array_f = []; // массив выбранных элементов фильтра
    jQuery(".filter__show-filter-item-like i").click(function(){
        jQuery(this).toggleClass("like_active");
        if(jQuery(this).hasClass("like_active")){
            jQuery(this).removeClass("fa-heart-o");
            jQuery(this).addClass("fa-heart");
            jQuery(this).parents(".filter__show-filter-item").find(".filter__show-filter-item-title").addClass("title-color");
            var item = jQuery(this).parents(".filter__show-filter-item").find(".filter__show-filter-item-title").text();
            array_f.push(item); // добавляем в массив выбранные элементы фильтрации
            console.log(array_f);
        };
        if(!jQuery(this).hasClass("like_active")){
            jQuery(this).addClass("fa-heart-o");
            jQuery(this).removeClass("fa-heart");
            jQuery(this).parents(".filter__show-filter-item").find(".filter__show-filter-item-title").removeClass("title-color");
            var item = jQuery(this).parents(".filter__show-filter-item").find(".filter__show-filter-item-title").text();
            array_f.splice( jQuery.inArray(item,array_f) ,1 ); // удаляем с массива элементы фильтрации
            console.log(array_f);
        }
        prodShow();
    });



    jQuery(".filter__show-filter-item-delete i").click(function(){
        jQuery(this).parents(".filter__show-filter-item").find(".filter__show-filter-item-like i").removeClass("like_active");
        jQuery(this).parents(".filter__show-filter-item").find(".filter__show-filter-item-like i").removeClass("fa-heart");
        jQuery(this).parents(".filter__show-filter-item").find(".filter__show-filter-item-like i").addClass("fa-heart-o");
        jQuery(this).parents(".filter__show-filter-item").find(".filter__show-filter-item-title").removeClass("title-color");
        var item = jQuery(this).parents(".filter__show-filter-item").find(".filter__show-filter-item-title").text();
            array_f.splice( jQuery.inArray(item,array_f) ,1 ); // удаляем с массива элементы фильтрации
            console.log(array_f);
        prodShow();
    });


    function prodShow(){

        const main_products = document.querySelector('.products');

        const products = document.querySelectorAll('.product');

        products.forEach(product => {
          const words = product.innerText.split(', ');
          let find_node = null;
          
          for (let i = 0; i < words.length; i++) {
            if (array_f.includes(words[i].toLowerCase())) {
              find_node = product;
              break;
            }

          }
          
          product.remove();
          
          if (find_node) {
            main_products.appendChild(find_node);
          }
        });
        console.log(main_products);
    }

</script>
1
  • Фильтровать удобнее данные. А ДОМ формировать из уже отфильтрованных 13 авг 2020 в 9:06

2 ответа 2

2

const need_words = ["авокадо", "сыр", "угорь"];

const main_products = document.querySelector('.products');

const products = document.querySelectorAll('.product');

products.forEach(product => {
  const words = product.innerText.split(', ');
  let find_node = null;
  
  for (let i = 0; i < words.length; i++) {
    if (need_words.includes(words[i].toLowerCase())) {
      find_node = product;
      break;
    }
  }
  
  product.remove();
  
  if (find_node) {
    main_products.appendChild(find_node);
  }
});
<div class="products">
  <div class="product">
    <span class="description">Сыр, чеснок</span>
  </div>
  <div class="product">
    <span class="description">Томат, капуста</span>
  </div>
  <div class="product">
    <span class="description">Огурец, помидор</span>
  </div>
  <div class="product">
    <span class="description">авокадо, помидор</span>
  </div>
</div>

4
  • Спасибо, но в моем случае получаю пустой блок products... Сейчас полностью код фильтра выложу
    – ilyaaa521
    13 авг 2020 в 9:26
  • @ilyaaa521 Вы цикл по словам проконсольте и посмотрите.
    – doox911
    13 авг 2020 в 9:56
  • по словам работает
    – ilyaaa521
    13 авг 2020 в 10:01
  • @ilyaaa521 так что тогда не работает?
    – doox911
    13 авг 2020 в 10:04
1

Для этих целей можно использовать метод filter.

const cases = ["авокадо", "сыр", "угорь"];

$(".product").filter(index => {
    const text = $(".description", this).text();
    for(let choice of cases){
        return text.indexOf(choice) != -1;
    }
    return false;
});
2
  • Спасибо за ответ, получаю false
    – ilyaaa521
    13 авг 2020 в 8:29
  • @ilyaaa521 ничего не выводит?
    – MaxLevs
    13 авг 2020 в 9:58

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge you have read our privacy policy.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.