Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
453 views
in Technique[技术] by (71.8m points)

javascript - Using JQuery to toggle div visibility

I'm writing some jquery code to toggle a Div visibility. I followed the method posted here: http://jsfiddle.net/Ga7Jv/.

When the user clicks an image (next to a H2 tag) i want it to toggle the div.

Here is the Jquery:

$(function()
{
$(".expander").live('click', function(){
        $(this).next("#TableData").slideDown();
        $(this).removeClass('expander');
        $(this).addClass('expanded');
});

$(".expanded").live('click', function(){
        $(this).next("#TableData").slideUp();
        $(this).removeClass('expanded');
        $(this).addClass('expander');
});

Here is the HTML:

<h3><img src="toggle.png" class ="expander" alt="Expand"/> 
Tabular Data</h3>
<div id="TableData">
//Content
</div>

The is css applied to the class expander and when i click the button it appears that the css changes, as i would expect. So i assume the code is finding the toggle button and switching out the classes alright.

However it doesn't perform the action i need, which is to slide the div up or down depending on that class.

The other way i've tried to achieve this is with this:

  $(function(){
     $('.expander').live('click',function(){
     $('#TableData').show();
     $('#TableData').hide();
        });

This only closes the div and does not open again when i click it. I've also had it so it closes fine but when i open it, it immediately closes again.

Thanks

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Problem with your code is that its last function call is .hide(), thus it will always hide the div

Simply use .toggle(), it display or hide the matched elements.

$(function(){
    $('.expander').live('click',function(){
        $('#TableData').toggle();
    });
});

Fiddle

OR

$(function () {
    $('.expander').live('click', function () {
        $('#TableData').slideToggle();
    });
});

Fiddle with slide

You can use .slideToggle(), if you want to display or hide the matched elements with a sliding motion


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...