jQuery .show() - show / hide for multiple elements

谁说我不能喝 提交于 2019-12-11 09:05:27

问题


I am trying to achieve this:

  1. Create a page with multiple lists, each containing a nested list to be revealed when a link is clicked.

  2. When a link is clicked, and the content is revealed, when clicking on another link, the previously revealed content is hidden, and the new one revealed.

  3. When clicking anywhere on the page away from the revealed content, this click will hide the item.

Here is a Pen showing the reveal action working as expected, but this does not function as I'd like so far.

http://codepen.io/juxprose/pen/pzvuC

Any pointers would be much appreciated.

Thanks.


回答1:


Try this:

$('.trigger').click(function (e) {
    e.stopPropagation();
    $('.show').hide();    
    $(this).next('.show').slideDown();
});

$(document).click(function () {
    $('.show').slideUp();    
});

FIDDLE DEMO




回答2:


This code should do what you want if I understood well :

html :

<ul id="listItems">
    <li><a href="#">Item1</a>
        <ul>
            <li>Item 1.1</li>
            <li>Item 1.2</li>
            <li>Item 1.3</li>
        </ul>
    </li>
    <li><a href="#">Item2</a>
        <ul>
            <li>Item 2.1</li>
            <li>Item 2.2</li>
            <li>Item 2.3</li>
        </ul>
    </li>
    <li><a href="#">Item3</a>
        <ul>
            <li>Item 3.1</li>
            <li>Item 3.2</li>
            <li>Item 3.3</li>
        </ul>
    </li>
</ul>

js :

$(document).ready(function() {
   $("#listItems ul").hide();
   $("#listItems a").on("click", function() {
       $("#listItems ul").hide();
       $(this).next().show();
   });
   $(document).click(function(e) {
    if ( $(e.target).closest('#listItems').length === 0 ) {
        $("#listItems ul").hide();
    }
   });
});



回答3:


Try this,

$('.trigger').click(function(){
    $('.show').slideUp();
    $(this).next('.show').slideDown(); 
});

Fiddle http://jsfiddle.net/8jedA/



来源:https://stackoverflow.com/questions/16811536/jquery-show-show-hide-for-multiple-elements

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!