In general, there is a small navigation from several links which I closed using e.preventDefault() . Link paths are category names. Below is a large block with a set of li elements that have an attribute class= {название категории к которой он относится} . Is it possible to make it so that when clicking on a link, its href is compared with the classes of li elements and those elements whose attributes do not match hide in display:none ? Or there is an easier algorithm to implement such an action.

 <a href="#cat1">ссылка</a> <a href="#cat2">ссылка</a> <a href="#cat3">ссылка</a> <ul> <li class="cat1"></li> <li class="cat1"></li> <li class="cat2"></li> <li class="cat2"></li> <li class="cat3"></li> <li class="cat3"></li> </ul> 
  • class can be only one? or maybe something like: <li class="cat1 cat-for-li"></li> ? - Grundy
  • Does everyone have one class? - Andrei
  • Or you can use something else instead of class, for example data-category - Andrey

1 answer 1

Like that

 $(function() { $('a').on('click', function(event) { event.preventDefault(); var cat = $(this).attr('href').substr(1); $('li').hide(); $('li.' + cat).show(); }); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <a href="#cat1">ссылка</a> <a href="#cat2">ссылка</a> <a href="#cat3">ссылка</a> <ul> <li class="cat1">1</li> <li class="cat1">1</li> <li class="cat2">2</li> <li class="cat2">2</li> <li class="cat3">3</li> <li class="cat3">3</li> </ul> 

  • How do I understand this option hides all li elements, and then opens those that have the prefix sat in the class? The problem is that in reality the category names will be completely different and will be inserted automatically into the path of the link and in the li class element belonging to this category. You must first get the value of href, then compare it with the class, and if they agree, then open it - Andrew
  • @ Andrei, what’s wrong with that? - Jean-Claude
  • $ ('li.' + cat) .show (); Does this mean open all li whose class starts with cat? - Andrei
  • @Andrey , As I understand it ... and then it opens up those that have the prefix sat in the class - you misunderstand. items are shown not with a prefix, but with a specific class. var cat = $(this).attr('href').substr(1); - the value of the variable cat , this is just the name of the class. which must be shown - Grundy
  • This class will change. - Andrei