简体   繁体   中英

How to toggle hide/show of all elements with same class name on button click

I'm trying to toggle hide/show on all divs with the same class. I have a few tables on my page with multiple strings in each row. I only show the first string and have the rest of the strings in a div that's hidden with style='display:none;'.

I just cannot get this to work. Any suggestions?

example of html:

<a href=# onClick='toggleHist(\"".$zone."\");return false;'>Additional Info</a>

    <table>
    <tr>
    <td>asdfasdf   <div class='zone_1' style='display:none;'>asdfasdf asdfasdf asdfasdf </div></td>
    </tr>
    <tr>
    <td>
     asdfasdf<div class='zone_1' style='display:none;'> asdfasdf asdfasdf asfasdf </div>
    </td>
    </tr>
    <tr>
    <td>
     adfasdf<div class='zone_1' style='display:none;'> asdfasdf asdfasdf asdfasdf </div>
    </td>
    </tr>
    </table>

My javascript:

function toggleHist(zone_name){
    //alert(zone_name);
    $('.'+zone_name).toggle();

}

Using .show(); and .hide(); both work, but toggle won't. What am I doing wrong?

As an alternative to .toggle()

You can create a css class containing display: none and use .toggleClass() to toggle that class on the elements.

.DisplayNone
{
    display: none;
}


function toggleHist(zone_name){

    $('.'+zone_name).toggleClass('DisplayNone');

}    

Or you can use show and hide by checking to see if the elements are visible.

function toggleHist(zone_name){    

    if ($('.'+zone_name).is(":visible")) 
         $('.'+zone_name).hide();        
    else
         $('.'+zone_name).show();

}   

如果show()工作, hide()工作,但toggle()不起作用,我只看到一个解释:你的事件被触发两次(或任何偶数)。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM