【问题标题】:jQuery to find nearest Div of ParentjQuery找到最近的父div
【发布时间】:2012-08-05 10:06:04
【问题描述】:

我正在尝试通过以下场景学习 jQuery。为此,我在阅读了多个 SO 问题后尝试了以下 jQuery;但它没有工作

$(this).closest('.viewLogText').parent().find('.reportLog').css("display", "none");

场景:

在具有 Css 类“repeaterRecord”的 div 中有三个子 div 元素。子 div 带有 css 类 - repeaterIdentifier、viewLogTitle 和 reportLog。

有两个具有这种结构的 div(具有 Css 类“repeaterRecord”的 div)。

带有viewLog类的div如下所示。

   <div class="viewLogTitle">
        <div class="viewLogText">
            View Report Log
        </div>
        <div>
            <img alt="Expand" src="Images/PlusIcon.GIF" class="expandLogIcon" />
            <img alt="Collapse" src="Images/MinusIcon.GIF" class="collapseLogIcon" />
        </div>
    </div>

当点击collapseLogIcon图像时,我需要(仅)隐藏最近的具有“reportLog”类的div(在“viewLogTitle”的同一级别)。我们如何使用 jQuery 来做到这一点?

更新的工作示例

http://jsfiddle.net/Lijo/L9w4F/11/http://jsfiddle.net/Lijo/L9w4F/8/http://jsfiddle.net/Lijo/L9w4F/12/

参考

  1. Efficient, concise way to find next matching sibling?

  2. jquery select siblings 'until'

【问题讨论】:

    标签: jquery next siblings


    【解决方案1】:

    您可以使用.siblings() 查找最近的div

    API HERE

    【讨论】:

      【解决方案2】:

      我建议使用:

      $(this).closest('.viewLogTitle').next('.reportLog').hide();
      

      请注意,传递给next() 方法('.reportLog')的过滤器意味着viewLogTitle 元素的下一个兄弟元素将受到影响只有它匹配该选择器。如果.viewLogTitle 的下一个兄弟总是 是目标(HTML 不会改变),则过滤器是不必要的,可以省略。

      或者,如果他们并不总是连续跟随(但“最近的”总是会受到影响),对于跟随兄弟姐妹:

      $(this).closest('.viewLogTitle').nextAll('.reportLog:first').hide();
      

      或者对于前面的兄弟姐妹(如果.reportLog.viewLogTitle 之前):

      $(this).closest('.viewLogTitle').prevAll('.reportLog:first').hide();
      

      参考资料:

      【讨论】:

      • 单个元素不需要next中的过滤选择器
      • 这是真的,就目前而言;但通过过滤器的目的是考虑到下一个兄弟可能不是成为所需目标的那些时间。不过,公平地说,我应该解释一下这个意图。 已编辑
      • 如果不是这样,那么next不合适:P
      • 是的,我什至评论的唯一原因是,任何时候我看到next 与过滤器一起使用,都是因为作者误解了nextnext(filter) 直观地看起来它会找到下一个匹配 filter 的元素,但它只是简单地获取下一个元素兄弟并在它匹配过滤器时返回它,否则什么也不返回。
      • 同意;你的评论是对的,我的解释是一个绝对明显的遗漏。 =)
      【解决方案3】:

      你可以使用siblings()方法:

      $(this).closest('.viewLogText').siblings('.reportLog').hide()
      

      你也可以试试hide()方法,和.css("display", "none");一样

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-03-20
        • 1970-01-01
        • 1970-01-01
        • 2017-11-20
        • 2011-01-19
        • 2012-05-15
        相关资源
        最近更新 更多