【问题标题】:Comments toggle button open multiple comments评论切换按钮打开多个评论
【发布时间】:2014-10-27 15:09:49
【问题描述】:

我在博客的“主”页面中有这个用于显示/隐藏 cmets 的脚本:albertosotophotography

<script type= "text/javascript">
    // Show/Hide Comments
    jQuery(document).ready(function() {

        // Get #comments div
        var uniqueAppend = 1;
        var tempName = 'comments';
        while(jQuery("#comments").length > 0 ){
            jQuery("#comments").attr('id',tempName + uniqueAppend++).addClass('commentContainer')
        }
        var commentsDiv = jQuery('.commentContainer');

        // Only do this work if that div isn't empty
        if (commentsDiv.length) {

        // Hide #comments div by default
        jQuery(commentsDiv).hide();

        // Append a link to show/hide
        jQuery('<a/>')
            .attr('class', 'toggle-comments')
            .attr('href', '#')
            .html('Notes')
            .insertAfter(commentsDiv);

        // Encase button in .toggle-comments-container div
        jQuery('.toggle-comments').wrap(jQuery('<div/>', {
            class: 'toggle-comments-container'
        }))     

        // When show/hide is clicked
      jQuery('.toggle-comments').on('click', function(e) {
            e.preventDefault();


        // Show/hide the div using jQuery's toggle()

        var commentContainer = jQuery(this).parent('.toggle-comments-container').siblings('.commentContainer');

        jQuery(commentContainer).fadeToggle('slow', function() {

            // change the text of the anchor
            var anchor = jQuery(commentContainer).siblings('.toggle-comments-container').children('.toggle-comments');
    var anchorText = anchor.text() == 'Notes' ? 'Hide' : 'Notes';
            jQuery(anchor).html(anchorText);

        });
        });

        } // End of commentsDiv.length

    }); // End of Show/Hide Comments
    </script>

问题是当我按下按钮同时打开所有帖子 cmets 时。 我只想打开我按下的按钮的 cmets。 如果有人可以帮助我,我将不胜感激。 谢谢和最好的问候。

阿尔伯托

【问题讨论】:

    标签: jquery button comments toggle


    【解决方案1】:

    更改以下行中的选择器将解决您的问题-

    问题

    var commentContainer = jQuery(this).parent('.toggle-comments-container').siblings('.commentContainer');
    var anchor = jQuery(commentContainer).siblings('.toggle-comments-container').children('.toggle-comments');
    

    解决方案

    var commentContainer = jQuery(this).parent().prev();
    var anchor = jQuery(commentContainer).next().children('.toggle-comments');
    

    问题在于使用 .siblings() 匹配具有相同类名的所有元素,从而选择所有评论节点。


    另外使用slideToggle而不是fadeToggle可能会给你更好的视觉体验(这行只是一个设计建议。与答案无关)

    【讨论】:

    • 非常感谢!它有效!感谢您的宝贵时间和问候
    猜你喜欢
    • 2014-03-29
    • 1970-01-01
    • 1970-01-01
    • 2011-07-24
    • 2014-08-30
    • 2011-05-20
    • 2014-01-30
    • 1970-01-01
    • 2011-09-03
    相关资源
    最近更新 更多