<...">

Php hide dynamically built element

i has ul with some li something like this

<?php
   for($i=0; $i<5; i++) { 
      $id_name = "link" . $i;
      echo "<ul><a href='#' id=$id_name >list</a>
               <li class='on'>1</li>
               <li class='on'>2</li>
               <li class='on'>3</li>
            </ul> ";
    }
?>

and css:

.off{display:none;} .on{display:block;}

I want every time I click a link to hide all the elements of lithis link. I tried jQuery with a function toggleClass(), but I can’t do anything, I don’t know the link identifier. I read something about functions child()and parent(). Can I use this method? (sorry for programming errors, I'm new to php)

+4
source share
3 answers

Why not give the link tag some class name as an example myLink, for example the following code:

echo "<ul><a href='#' id=$id_name class='myLink'>list</a>
           <li class='on'>1</li>
           <li class='on'>2</li>
           <li class='on'>3</li>
        </ul>

jquery myLink .siblings() A li. .child() .parent(). :

$(document).on('click', '.myLink', function () {
  $(this).siblings().toggleClass('off');
});

, on li, toggleClass('off') off, on. , css:

.off {
  display:none !important;
} 

DEMO

p/s: A , UL

+2

Try:

$('a').click(function(){
 $(this).parent().find('li').toggleClass('off');
});

:

 $('a').click(function(){
     $(this).parent().children('li').toggleClass('off');
    });

:

$('a').click(function(e){
  e.preventDefault();
     $(this).nextAll('li').toggleClass('off');
    });
+1

jquery, html. ( - css). , .

$(document).ready(function() {
  $('a').click(function() {
    $(this).parent().children('li').toggle();
  });
});
+1

Source: https://habr.com/ru/post/1619166/


All Articles