Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/416.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何仅为子元素运行jQuery函数?_Javascript_Jquery_Html_Css - Fatal编程技术网

Javascript 如何仅为子元素运行jQuery函数?

Javascript 如何仅为子元素运行jQuery函数?,javascript,jquery,html,css,Javascript,Jquery,Html,Css,我试图在单击嵌套在父注释中的图标时折叠所有子注释,包括父注释 使用下面的jQuery代码,我能够将注释框折叠起来,但是现在位于另一个部分中的注释也被折叠起来 jQuery代码- $('.comment-toggle pre').on('click', function(e) { $(".single-comment-wrapper .comment-text, .single-comment-wrapper .comment-bottom, .single-comment-outer .

我试图在单击嵌套在父注释中的图标时折叠所有子注释,包括父注释

使用下面的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太长了。我已经创建了一个代码笔。下面是它的直接链接


提前谢谢。

我想,你应该为div使用不同的类。因为当您单击.content togle类时,javascript代码会对所有.single comment wrapper.comment text、.single comment wrapper.comment bottom、.single comment outer.child comment类执行操作。

div的结构使这一操作变得棘手,我已经在小提琴上玩了大约10分钟,并且想出了这个主意——它的方向是正确的,但并不完美

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

所有的加号和减号都会更改,因为当前代码的目标是类,它需要更改为相对于+/-单击的so$(此)。etc

更新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元素的上下文中包含子元素,那么使用它将更容易。基于
ul
的树状视图将简化标记并减少HTML元素的数量。

感谢您的回答,但不幸的是,您的代码工作得并不完美。问题仍然存在-a)现在当评论被折叠时,它看起来像这样-但是我希望它看起来像这样-b)当我点击第二个评论-()时,它是它下面所有评论的父评论,它也折叠上面的评论。更新的答案。现在,每个注释都会保存其状态,并在折叠时隐藏注释内容。结束您可以删除父注释类。