在jQuery中切换wordpress中的活动和非活动div

时间:2015-07-16 06:10:38

标签: javascript jquery html wordpress

在wordpress类别页面中,我希望在帖子中切换活动和停用类。

当我点击“阅读更多”按钮时,删除课程停用并添加课程活动

使用代码:

它在循环中

 <div class="post-content deactivate" id="postfull_con<?php echo $postid; ?>" >
                <?php the_content();?>
            </div>

<div class="post_less" id="post-<?php echo $postid; ?>">
                <p>Read more </p>
            </div>

循环结束

jQuery(document).ready(function() {
jQuery('#post-<?php echo $postid; ?>').on('click', function() {
     if(jQuery('#postfull_con<?php echo $postid; ?>').hasClass('active')){
           jQuery('#postfull_con<?php echo $postid; ?>').removeClass('active');
           jQuery('#postfull_con<?php echo $postid; ?>').addClass('deactivate');
        }else{
           jQuery('#postfull_con<?php echo $postid; ?>').addClass('active');
           jQuery('#postfull_con<?php echo $postid; ?>').removeClass('deactivate');
        }
        });
});

当我点击其他帖子时,问题是它没有停用(阅读更多)

1 个答案:

答案 0 :(得分:1)

.post-content {}应该具有停用类

的CSS规则

HTML:

<div class="post-content" id="postfull_con<?php echo $postid; ?>" >
    <?php the_content();?>
</div>

<div class="post_less" data-id="<?php echo $postid; ?>">
    <p>Read more </p>
</div>

JS:

您不需要对每个帖子ID进行绑定。

$(document).ready(function() {
    $('.post-less').on('click', function() {
        var postId = $(this).data('id');

        //Close all other open posts
        //It's a bad practice to remove one class to add another for a specific funtionality to happen
        //The default state of post-content should be the "deactivate" class and when you add active rules should be overwriten.
        $('.post-content').removeClass('active');

        //Look for the full post and activated
        $('#postfull_con' + postId).addClass('active');
    });
});