4

我正在尝试通过以下场景学习 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. 找到下一个匹配的兄弟姐妹的有效,简洁的方法?

  2. jquery选择兄弟姐妹'直到'

4

3 回答 3

5

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

API在这里

于 2012-08-08T10:03:02.510 回答
2

我建议使用:

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

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

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

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

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

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

参考:

于 2012-08-08T10:04:22.920 回答
1

您可以使用siblings()方法:

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

您也可以尝试与以下hide()相同的方法.css("display", "none");

于 2012-08-08T10:04:52.437 回答