Display Child Categories on click

2019-03-03 02:05发布

问题:

On my wordpress website I have a menu that displays the subcategories for each categorie. What I want to do is to hide the subcategories by default and display them only when I click on the parent category.

My HTML:

<ul class="scrolling cat mCustomScrollbar _mCS_2 mCS-autoHide" style="position: relative; overflow: visible;">
<div id="mCSB_2" class="mCustomScrollBox mCS-minimal-dark mCSB_vertical mCSB_outside" style="max-height: 145px;" tabindex="0">
<div id="mCSB_2_container" class="mCSB_container" style="position: relative; top: -240px; left: 0px;" dir="ltr">
<li class="cat-item cat-item-31">
<a href="https://www.website.com/option">Option</a> <span>11</span>
<ul class="children">
<li class="cat-item cat-item-10867">
<a href="https://www.website.com/option2">Another option</a> <span>0</span>
</li>
</ul>
</li>

My functions.php

function categorias() {
$args = array('hide_empty' => FALSE, 'title_li'=> __( '' ), 'show_count'=> 1, 'echo' => 0 );             
$links = wp_list_categories($args);
$links = str_replace('</a> (', '</a> <span>', $links);
$links = str_replace(')', '</span>', $links);
echo $links;  } 

Any ideas? Thanks.

回答1:

Use Css to hide them:-

ul.children{
  display:none;
}

And then use jQuery to open them:-

jQuery('li.cat-item').on('click',function(){
   $('ul.children').hide();
   $(this).find('ul.children').show();
});


回答2:

Use This Css as below

 <style>     
ul.children{display:none}
</style>

In Javascript:

<script type="text/javascript">
$('.cat-item').click(function()
{
    if($(this).find('ul.children'))
    {
        $(this).find('ul.children').toggle();
    }
});
</script>