2015-10-05 57 views
2

我的网站是一个博客,我有一个页面,其中包含一个HTML页面上的所有帖子。 “帖子”只是div中的图像,我需要一些信息才能够显示和隐藏图像的父div。继承人如何其设置:如何显示隐藏div divs很容易?

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和引导太

回答

2

改变你的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类或数据属性。

+0

我是JS新手,非常感谢!不知道这是否存在。 –

+0

问题是,您不会阅读文档,而只是试图找到正确的解决方案。 – Joerg

0

您可以使用event.target/this指当前对象点击,找到你发现() 或

检查为孩子们点击的对象的子(展开/预览),如果它是.expand /.preview函数是()//不是更好的方法

$(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() 
    }); 
});