【问题标题】:How to show hide divs INSIDE divs easily?如何轻松显示隐藏 div INSIDE div?
【发布时间】:2015-10-06 06:02:11
【问题描述】:

我的网站是一个博客,其中有一个页面,所有帖子都在一个 HTML 页面上。 “帖子”只是 div 中的图像,我需要一些信息才能在图像的父 div 中显示和隐藏。以下是它的设置方式:

HTML

<div class="posts">
    <h3>mm/dd/yy<p class="preview">click to show more</p><p class="expand">click to show less</p></h3>
    <h4>Title</h4><br>
    <p class="expand">caption caption caption caption caption caption caption caption caption</p>
    <div class="centertext">
        <img class="post" src="path/to/image">
    </div>
    <br>
</div>

小CSS

.expand{显示:无;}

JS

$(document).ready(function(){
$(".posts").click(function(){
    $('.expand').toggle();
    $('.preview').toggle();
});

我不希望发生的最终结果是,当我单击一个图像时,所有图像及其标题都会隐藏和显示。显示here 或全屏here 有人请帮助我!附加信息:我也在使用 JQuery 和 Bootstrap

【问题讨论】:

    标签: javascript jquery html css


    【解决方案1】:

    把你的 JS 改成:

    $(document).ready(function () {
        $(".posts").click(function () {
            $(this).find('.expand').toggle();
            $(this).find('.preview').toggle();
        });
    
    });
    

    或者更简单:

    $(document).ready(function () {
            $(".posts").click(function () {
                $(this).find('.expand, .preview').toggle();
            });
    
        });
    

    切换意味着您不知道状态。最好的方法是更改​​ css 类或数据属性。

    【讨论】:

    • 我是 JS 新手,非常感谢!不知道这存在。
    • 重点是,您没有阅读文档,您只是想获得正确的解决方案。
    【解决方案2】:

    您可以使用 event.target/this 来引用当前单击的对象,并使用 find() 查找您单击的对象的子对象(展开/预览) 或

    检查孩子是否是.expand/.preview with function is() //不是更好的方法

    $(document).ready(function () {
        $(".posts").click(function () {
            $(this).find('.expand').toggle();
            $(this).find('.preview').toggle();
        });
    });
    
    or
    
    $(document).ready(function () {
        $(".posts").click(function (event) {
            $(event.target).find('.expand').toggle();
    //check if target is .expand or its child then first go to its parent with .parents().eq() then apply find()
            $(event.target).find('.preview').toggle();
    //check if target is .preview or its child then first go to its parent with .parents().eq() then apply find()
        });
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-05-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多