douhuang75397 2015-11-10 05:24 采纳率: 0%
浏览 54
已采纳

使用jquery显示和隐藏

There are number of examples for add and remove in jquery. But my code is bit different to examples. when i click add it show second and if i click again on add i want show third as well as when i click remove hide the third also until five. Here is my code

CSS

#second {
    display: none;
}
#third {
    display: none;
}
#forth {
    display: none;
}
#fifth {
    display: none;
}

HTML

<div id="header">
     <a href="#" id="add1">add</a> - <a href="#" id="remove">remove</a>
    <div id="first"><a href="#">first</a></div>            
    <div id="second"><a href="#">second</a></div>
    <div id="third"><a href="#">third</a></div>
    <div id="forth"><a href="#">forth</a></div>
    <div id="fifth"><a href="#">fifth</a></div>
</div>`

JavaScript

$(document).ready(
    function() {
        $("#add1").click(function() {
            $("#second").show();
        });
        $("#remove").click(function() {
            $("#second").hide();
        });
    });

HERE IS CODE JSfiddle

  • 写回答

1条回答 默认 最新

  • dsag14654 2015-11-10 05:30
    关注

    Here is an approach you can use. First, add a class to all elements that you want to show / hide. In this case I used class toggle:

    <div id="header">
        <a href="#" id="add1">add</a> - <a href="#" id="remove">remove</a>
        <div id="first" class="toggle"><a href="#">first</a></div>            
        <div id="second" class="toggle"><a href="#">second</a></div>
        <div id="third" class="toggle"><a href="#">third</a></div>
        <div id="forth" class="toggle"><a href="#">forth</a></div>
        <div id="fifth" class="toggle"><a href="#">fifth</a></div>
    </div>
    

    Then when you are adding an element, use function first to find first not visible element with class toggle and show it. When you want to remove element, use function last to find last not visible element and hide it:

    $(document).ready(function() {
        // when add is clicked, show first not visible element with class 'toggle'
        $("#add1").click(function() {
            $('.toggle:not(:visible)').first().show();
        });
        // when remove is clicked, hide last visible element with class 'toggle'
        $("#remove").click(function() {
            $('.toggle:visible').last().hide();
        });
    });
    

    Here is updated JSFiddle

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 机器学习能否像多层线性模型一样处理嵌套数据
  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效