简体   繁体   中英

Hide All div's except the one clicked

I have several div's and inside each div i have ul's and li's . I have this code working, when user click on some li it will show a div inside this li .

What i need is to let showed the div that the user clicked one, and close the others.

Can you help?

Javascript code:

$(document).ready(function() {
$('li').each(function() {
    var tis = $(this), state = false, answer = tis.next('#terms, #articlesAnswers').hide().css('height','auto').slideUp();
    tis.click(function() {
        state = !state;
        answer.slideToggle(state);
        tis.toggleClass('active',state);
    });
});
});

HTML Code:

<ul id="termsArticles">
            <li>Article 1 – Registration, account management and rescission</li>
                <div id="terms">
                    <ul>
                        <li>Access conditions and registration</li>
                            <div id="articlesAnswers">
                                test text!
                            </div>
                        <li>Account Management</li>
                            <div id="articlesAnswers">
                                test text!
                            </div>
                    </ul>
                 </div>

<li>Article 2 – Free services</li>
  <div id="terms">
     <ul>
         <li>publish an ad for a project or event</li>
          <li>apply to an ad</li>
     </ul>
 </div>

DEMO

Working fiddle: http://jsfiddle.net/7W7y9/7/

I changed your markup though, since it did not make any sense. Don't ever use the same ID twice, take CLASS names instead.

JavaScript now ends up looking like this:

$(document).ready(function() {
    $("li").click(function(e) {
    $(this).parents(".terms").find(".articlesAnswers").hide();
    $(this).children(".articlesAnswers").show();
  });
});

Don't use duplicate ID's on one page. It is incorrect.
CSS:

.active+.terms{height:auto;}
 .articlesAnswers{display:none;}
 .active+.articlesAnswers{display:block;}

JS

$(document).ready(function() {
  $("#termsArticles li").click(function(){
    if ($(this).hasClass('active')){
        $(this).toggleClass('active')
    } else {
        $(this).parent().find('>li').removeClass('active');
        $(this).addClass('active');
    }
})

});

DEMO
For slide effect i created 2 variant of code: with CSS3 and with JQ .

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