使用parent()和next()选择器的jQuery问题

Amr*_*mra 2 jquery parent next

我有以下代码:

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <title>Untitled Page</title>
    <script class="jsbin" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
    <script type="text/javascript">
    $(document).ready(function(){
        $(".Note").click(function(){
        $(this).parent().parent().next(".divNote").slideToggle();
        });
    });
    </script>

  </head>
  <body>
    <table>
        <tr>
            <td class="Note" style="cursor: pointer">
                <font size="3" color="#800080"><b><u>TD</u></b> </font>
            </td>
        </tr>
    </table>
    <br />
    <div style="display: none" class="divNote">
    </div>
  </body>
</html>
Run Code Online (Sandbox Code Playgroud)

我可以弄清楚为什么它不起作用。

示例:这里

任何帮助。

Rob*_*nik 6

让我解释一下为什么它不起作用

您已添加了一个过滤器以next()仅过滤出匹配的元素。在您的情况下,它仅包含一个br没有匹配类名的元素(),因此结果集被截断为零个元素。

使其运作的方式

因此,next您不仅要过滤元素,还必须从所有同级对象中过滤掉:

$(document).ready(function() {
  $(".Note").click(function(){
    $(this).parents("table").siblings(".divNote").slideToggle();
  });
});
Run Code Online (Sandbox Code Playgroud)

或从所有下一个兄弟姐妹中过滤掉(以前的兄弟姐妹根本不相关时)

$(document).ready(function() {
  $(".Note").click(function(){
    $(this).parents("table").nextAll(".divNote").slideToggle();
  });
});
Run Code Online (Sandbox Code Playgroud)