2010-09-10 85 views
1

我正嘗試做一些我在WordPress中沒見過的東西。基本上,當你到達博客時,會顯示標題,縮略圖和摘錄。當按下切換按鈕時,帖子應該向下滑動以顯示內容。 (<?php the_content(); ?>使用jquery切換wordpress中的文章

這裏是我的Jquery:

$(document).ready(function() { 
      $('span.play a').click(function() { 
       if ($('.toggleSection').is(":hidden")) 
       { 
        $('.toggleSection').slideDown("slow"); 
       } else { 
        $('.toggleSection').slideUp("slow"); 
       } 
       return false; 
      }); 
    }); 

它完美!然而;由於切換位於wordpress循環中,只要按下切換按鈕,所有的切換都會打開。例如,如果我在頁面上有10個帖子,並且單擊一個切換按鈕,則會打開所有切換。這裏是我的WP循環:

<?php if(have_posts()) : while(have_posts()) : the_post(); ?> 
       <div class="post" id="<?php the_ID(); ?>"> 
        <div class="thumbnail"> 
         <?php the_post_thumbnail('mainimg'); ?> 
         <span class="play"><a href="#" onclick="jQuery('#comments').toggle();"><img src="<?php echo bloginfo('template_url'); ?>/images/play.png" width="30" height="36" alt="Play Video"></a></span> 
        </div> 


        <h2><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h2> 
        <h3>Posted in: <span><?php the_category(', ') ?> </span>On: <span><?php the_time('l, F jS, Y') ?></span></h3> 

        <div class="entry"> 
         <p><?php the_excerpt(); ?> </p> 
        </div> <!-- entry --> 

        <div class="toggleSection"> 
        <p><?php the_content(); ?> </p> 
        </div> 



       </div> <!-- .post --> 

       <?php endwhile; ?> 

你在上面看到的,是點擊span.play A時,togglesection向下滑動,揭示的內容。當選擇任何一個切換時,將顯示所有內容。我喜歡它,因此每個切換在WP循環內都是唯一的,並且只顯示條目的內容。有任何想法嗎?

您可以在此處看到我的工作演示:http://vitaminjdesign.com/littlewindow/按縮略圖上的播放按鈕切換!

回答

4

您可以瘦下來你當前的代碼,並切換所有的人都這樣解決問題:

$(function() { 
    $('span.play a').click(function() { 
    $(this).closest('.post').find('.toggleSection').slideToggle(); 
    return false; 
    }); 
}); 

這上升到使用.closest()那麼.post元素做了.find()得到.toggleSection裏面只有.post。然後,可以將切換代碼濃縮爲僅調用.slideToggle()。以上爲中心,使用當前元素$(this),然後遍歷以找到使用tree traversal functions後的元素。

+0

Nick!你已經回答了我的一些問題,並且你總是發現。謝謝! – JCHASE11 2010-09-10 19:37:13