开发者

jQuery show/addClass for many div with same class

So what I'm tring to do:

HTML code:

<div class="div_with_content">
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Morbi congue 
lectus sed tortor placerat quis porttitor dui vehicula. Morbi molesti开发者_StackOverflow中文版e 
tortor sit amet eros tempor consectetur.
</div>
<div class="show_more_btn">Show more</div>

<div class="div_with_content">
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Morbi congue 
lectus sed tortor placerat quis porttitor dui vehicula. Morbi molestie 
tortor sit amet eros tempor consectetur.
</div>
<div class="show_more_btn">Show more</div>

<div class="div_with_content">
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Morbi congue 
lectus sed tortor placerat quis porttitor dui vehicula. Morbi molestie 
tortor sit amet eros tempor consectetur.
</div>
<div class="show_more_btn">Show more</div>

CSS Code:

.showMore
{
    display:block;
}
.div_with_content
{
    display:none;
}

So i got plenty of divs with class "div_with_content"(witch are not displayed) with some content, usually text. Below each "div_with_content" there is a button wrapped in div "show_more_btn". So when i press on div show_more_btn there will be style added (trought addClass in jQuery) of class showMore to show this div slowly. So its easy to achieve:

JS CODE:

$(function() {
        $(".show_more_btn").click(function(event){
               $(".div_with_content").addClass("showMore").show(1500,"swing");
     });
    });

But there is only one problem: when I press whichever show_more_btn all div_with_content are slowly shown, not only one precisely over show_more_btn. So what i want: when i press "show_more_btn" only "div_with_content" precisly over "show_more_btn" is going to be shown others "div_with_content" are still not visible. How do I achieve that ?


You just need to fix your javascript code so that it will only apply to the div_with_content that you want, and not all of them. Try this:

$(function() {
        $(".show_more_btn").click(function(event){
               $(this).prev(".div_with_content").addClass("showMore").show(1500,"swing");
     });
    });


http://api.jquery.com/prev/

you are looking for the prev() method of jquery. it will take a selector as well and will only select the class that was previous to the one clicked.

 $(".show_more_btn").click(function(event){
               $(".show_more_btn").prev(".div_with_content").addClass("showMore").show(1500,"swing");

something along those lines.


You can use prev http://api.jquery.com/prev/

$(function() {
     $(".show_more_btn").click(function(event){
               $(this).prev(".div_with_content").addClass("showMore").show(1500,"swing");
     });
});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜