开发者

Jquery Basic Beginner Question: How do i make my function reusable?

I have spent the last few hours attempting to do this on my own, and using Google to find a solution but to no avail.

So if you can help out i would super appreciate it!

Basically I have a page which has 3 separate biographies in 'preview mode', which shows only the first paragraph of each bio.

When you click on 'read more' for one bio it opens up the 'full mode'.

What is happening at the moment, is if i click on one 'read more' link, it opens up the full mode on all 3 bio's.

How do i edit the following code so;

  • It only opens the full mode bio of the link i click on
  • Make it reusable so i don't have to duplicate开发者_如何学Python the code 3 times for each bio

code:

$("a#btnReadMore").click(function() {
    $('.readMoreSlider').slideToggle("fast");
    $(this).toggleClass("readMoreSliderActive"); 
    return false;
});

Thanks for your help!


This depends on what your markup looks like. IDs need to be unique. I'm going to assume:

<div class="bio">
  <p>...</p>
  <a class="readMore" href="#">read more</a>
  <div class="more">
    <p>...</p>
    <p>...</p>
    <p>...</p>
  </div>
</div>

with CSS:

div.more { display: none; }

and Javascript:

$(function() {
  $("a.readMore").click(function() {
    $(this).next("div.more").slideToggle();
    return false;
  });
});


$("a.btnReadMore").click(function(){ 
//--^ - Make 'btnReadMore' a CSS class, not an ID

  // with this you reference *all* elements of class 'readMoreSlider', 
  // but you want only a single one
  $('.readMoreSlider').slideToggle("fast"); 

  // this should be okay
  $(this).toggleClass("readMoreSliderActive"); 
  return false; 
});

So if you have, hypothetically:

<div class="bio">
  <div class="readMoreSlider">The bio Text...</div>
  <a class="btnReadMore">Read more</a>
</div>

You would need this modification to find the right readMoreSlider for a certain click.

$(this).parent('.bio').find('.readMoreSlider').slideToggle("fast"); 

Depending on your actual markup, your's might look a bit differently.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜