Поиск тегов через запятую по атрибуту данных - PullRequest
0 голосов
/ 29 января 2019

У меня есть поле поиска, в которое я ввожу теги (разделенные запятой несколько тегов)

Я хотел бы найти каждый тег в атрибуте данных div, если он найден, и показать, что div в противном случае скрывает его.

HTML CODE

<div class="profile-listing">


<div data-tag="a b" class="profile"></div>


<div data-tag="b c" class="profile"></div>


<div data-tag="a c" class="profile"></div>


<div data-tag="d c" class="profile"></div>

</div>

jQuery("#search_tag").keyup(function(){


var string_filter = jQuery(this).val();
var array_filter = string_filter.split(',');
var filter = jQuery(this).val(), count = 0;

jQuery(".profile_listing .profile").each(function(){

   jQuery.each( array_filter, function( intValue, currentFilter ) {
        if(jQuery(".profile").indexOf(currentFilter) >-1){jQuery(this).show(); }else{ 
        jQuery(this).hide();
    }

    });

});

});

Случай:

Если я введу в поле поиска "a", то div, который содержит значение тега данных "a", должен выглядеть как профиль div (1,3), и если я введу a,b тогда должно отобразиться число деления (1,2,3).

Справка по любому фильтру jquery.

Спасибо

1 Ответ

0 голосов
/ 29 января 2019

Вы можете выполнить итерации по элементам dom, чтобы достичь этого.

Используемые здесь понятия:

Для - каждый цикл подробнее об этом здесь

сравнение строк подробнее об этом здесь

JavaScript Split подробнее об этом здесь

// this is your input 
var input = 'a,b';

// Split the input by comma
var profileSplit = input.split(',');

// iterate through all div which has class 'profile'
$('.profile').each(function(i, obj) {
  
  // hide the objects by default
  $(obj).hide();
  
  // retrive the data-tag value
  var tagVal = $(obj).data('tag');
  
  // iterate through your 'input' which as split by , earlier
  profileSplit.forEach(function(item) {
    //check if 'data-tag' value  with the input
    if (tagVal.indexOf(item) >= 0) {
      // show the div. 'obj' is the reference to the current div iteration
      $(obj).show();
      
      console.log(tagVal)
    }
  });

});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.1/jquery.min.js"></script>

<div class="profile-listing">


  <div data-tag="a b" class="profile">one</div>


  <div data-tag="b c" class="profile">two </div>


  <div data-tag="a c" class="profile">three</div>


  <div data-tag="d c" class="profile">four</div>

</div>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...