Toggle excerpt and content using jQuery

2020-07-30 03:54发布

问题:

I've seen this link: Toggle Posts in wordpress using jquery but it's unfortunately not doing what I want. I have a custom post type. What I want is to have an excerpt with "Read More" link. I got that. But I want the Read More link to toggle/slideToggle the full content within the article. Also have a "read less" link that will go back to showing the excerpt.

Edit: Here is the script I got working...can anyone tell me if this is too much. It works now, but I don't know if there is an easier way.

    $(function() {
    $('.content').hide()
  $('a.read').click(function() {
     $(this).closest('.tenant').find('.content').slideDown('fast');
     $('.excerpt').hide()
     return false;
  });
  $('a.read-less').click(function() {
     $(this).closest('.tenant').find('.excerpt').slideToggle('fast');
     $('.content').hide()
     return false;
  });
});

Then my query:

    <?php query_posts('post_type=tenants'); ?>
    <?php if ( have_posts() ) while ( have_posts() ) : the_post(); ?>
    <article class="tenant">
        <div class="tenant-header">
        <?php the_post_thumbnail('thumbnail', array('class' => 'left')); ?>

             <h1><?php the_title();?></h1>
            </div>
     <div class="excerpt"><?php the_excerpt(); ?><a href="" class="read">Read More</a>  </div>
     <div class="content"><?php the_content(); ?><a href="" class="read-less">Read Less</a></div>
     </article>

 <?php endwhile; ?>

EDIT AGAIN: When multiple posts are in, and you hit "read more" the text from the other post disappear :-/ So i guess this "almost" the right code

回答1:

Yes you were close, but using $('.excerpt').hide(); will hide all elements in the page with class excerpt that's why you need to reference the clicked element and find the appropriate content inside the article to show/hide:

 $(function () {
     $('.content').hide();
     $('a.read').click(function () {
         $(this).parent('.excerpt').hide();
         $(this).closest('.tenant').find('.content').slideDown('fast');
         return false;
     });
     $('a.read-less').click(function () {
         $(this).parent('.content').slideUp('fast');
         $(this).closest('.tenant').find('.excerpt').show();
         return false;
     });
 });