2017-08-16 31 views
0

我试图折叠所有的孩子评论,包括父母评论时,当一些点击图标嵌套在家长评论内的评论。如何仅为子元素运行jQuery函数?

使用下面的jQuery代码,我能够获得评论框折叠,但现在另一部分内的注释也崩溃了。

jQuery代码 -

$('.comment-toggle pre').on('click', function(e) { 
    $(".single-comment-wrapper .comment-text, .single-comment-wrapper .comment-bottom, .single-comment-outer .child-comment ").slideToggle('fast', function() { 
     if ($(this).is(':visible')) { 
      $(".comment-toggle pre").text('[–]'); 
     } else { 
      $(".comment-toggle pre").text('[+]'); 
     } 
    }); 
}); 
$('.comment-toggle pre').on('click', function(e) { 
    $('.single-comment-wrapper .left-side').slideToggle('fast'); 
}); 

由于HTMLand CSS太长。我创建了一个codepen。以下是它的直接链接。

https://codepen.io/anon/pen/Vzrvbm

在此先感谢。

回答

-1

我认为,你应该使用不同的div类。因为当你点击.content-togle类时,javascript代码会执行所有的动作.single-comment-wrapper .comment-text,.single-comment-wrapper .comment-bottom,.single-comment-outer .child-comment classes。

0

您的div的结构使得这个棘手的,我一直在玩弄在捣鼓〜10分钟,并都拿出了这一点 - 它在正确的方向前进,但并不完美......

$('.comment-toggle pre').on('click', function(e) { 
    $(this).parents('.single-comment-wrapper').next().slideToggle('fast', function() { 

所有的加号和减号都会改变,因为当前你的代码是针对类的,它需要改变为相对于+/-点击的$(this)。等

0

更新您的jQuery搜索相应的元素,你点击的元素:

$('.comment-toggle pre').on('click', function(e) { 

    // find main comment element 
    var rootComment = $(this).closest('.single-comment-wrapper'); 

    // hide child comments of current comment 
    var children = rootComment.parent().find('>.child-comment'); 
    children.slideToggle('fast'); 

    // hide left part 
    rootComment.find('.left-side').slideToggle('fast'); 

    // hide current comment 
    rootComment.find('.comment-text').toggle('fast', function() { 
    if ($(this).is(':visible')) { 
     rootComment.find(".comment-toggle pre", this).text('[–]'); 
     } else { 
      rootComment.find(".comment-toggle pre", this).text('[+]'); 
     } 
    }); 
}); 

另外,如果你可以改变的标记儿童包括主comment元素的context元素这将是更容易与...合作。基于ul的树状视图将简化标记并减少HTML元素的数量。

+0

感谢您的回答,但不幸的是,您的代码无法正常工作。问题仍然存在 - a)现在,当评论崩溃时,它看起来像这样 - http://i.imgur.com/BmL5tOX.png,但我想它看起来像这样 - https://我。 imgur.com/P7mhuYc.png b)当我点击第二个评论 - (https://i.imgur.com/E6D7B4E.png),它是下面所有评论的家长评论,它是折叠上面的评论它也是如此。 – rowdy

+0

已更新的答案。现在每个评论都会保存它的状态,并且隐藏评论的内容也会隐藏。结束,您可以移除“parent-comment”类。 – Samich