2017-08-03 26 views
0

我使用wordpress和學習jquery,我有一些問題。 我從foreach循環的類別中獲得帖子,並且我添加了一個帶有jquery函數的按鈕以顯示更多信息(切換函數),但該函數始終顯示第一個帖子的描述,即使我點擊其他按鈕。 例如:我點擊第三篇文章的按鈕,但是它是第一篇文章的描述。jquery和wordpress按鈕

<?php 
          global $post; 
          $args = array('posts_per_page' => -1, 'offset'=> 1, 'category' => 264); 

          $myposts = get_posts($args); 
          foreach ($myposts as $post) : setup_postdata($post); ?> 
            <div class="post-container"> 
              <div class="post-thumbnail"><?php the_post_thumbnail() ?></div> 
              <h3><?php the_title(); ?></h3> 
              <button id="know-more" class="all-button" onClick="Myfunction();">En savoir plus</button> 
              <div class="all-car" id="the-content"><?php the_content(); ?></div> 
            </div> 
          <?php endforeach; 
          wp_reset_postdata();?> 

和我的jQuery函數

(function(){ 
    Myfunction = function(){ 
      ("#the_content").toggle(500); 
    }; 
})(jQuery); 
+0

它看起來像正在裏面生成每個博克的-content'的ID',這意味着它會重複。 Id屬性是唯一的標識符。因此,他們預計在文檔中是獨一無二的。至少你需要檢查你的邏輯,並用類替換任何重複的id,這可以重複。 – Taplar

+0

我也注意到你的javascript IIFE沒有'$'參數來接受傳入的jQuery,而你的選擇器在它前面缺少'$'。 – Taplar

+0

我嘗試了一個類(.all-car),但問題所有生成的div有相同的類,所以最後它顯示的描述,但所有這個帖子@Taplar – matheo972

回答

1

ID屬性是唯一標識符閱讀差異here

如果你的HTML結構總是相同的按照上面再使用。

使$參考jQuery,不需要做功能,只需使用類選擇器綁定click事件並顯示按鈕後的下一個div。

$(document).ready(function() { 
 
    $('.all-button').on('click', function() { 
 
    $(this).next('.all-car').toggle(500); 
 
    }); 
 
});
.all-car { 
 
    display: none 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js"></script> 
 

 

 
<button class="all-button">En savoir plus</button> 
 
<div class="all-car">Lorem ipsum 1</div> 
 

 
<button class="all-button">En savoir plus</button> 
 
<div class="all-car">Lorem ipsum 2</div>