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

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

报告相同问题?

悬赏问题

  • ¥15 关于#python#的问题:求帮写python代码
  • ¥15 LiBeAs的带隙等于0.997eV,计算阴离子的N和P
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
  • ¥15 来真人,不要ai!matlab有关常微分方程的问题求解决,
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿
  • ¥15 回答4f系统的像差计算
  • ¥15 java如何提取出pdf里的文字?