2017-08-03 71 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>