为什么nearest()在遍历树之前找到第一个自身元素

P. *_*ank 6 html javascript jquery

我寻找为什么closest()在遍历树之前找到第一个自己的元素.

例如:当我点击children元素时,我想要fadeOutdiv元素,但是children元素太多了div,那么孩子们也是如此fadeOut

$(document).on("click", ".close", function() {
  $(this).closest("div").fadeOut();
});
Run Code Online (Sandbox Code Playgroud)
.feed {
  width: 200px;
  height: 200px;
  background: red;
  position: relative;
}
.close {
  position: absolute;
  top: 0;
  right: 0;
}
Run Code Online (Sandbox Code Playgroud)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="feed">
  <div class="close">
    X
  </div>
</div>
Run Code Online (Sandbox Code Playgroud)

为什么本身元素是谁fadeOut而不是父div元素?

我知道parent()得到父元素,但是closest()应该遍历元素树.

你有一个具体的案例,在哪里得到它自己有用?

Jos*_*ier 7

这是因为该.closest()方法以当前元素开始遍历DOM.您可能需要该.parents()方法,因为它将以父元素开头.

$(this).parents("div").fadeOut();
Run Code Online (Sandbox Code Playgroud)

值得注意的是,该.parents()方法返回零个或多个元素,而.closest()返回零个或一个元素.因此,您可能希望.first().parents()方法之后链接以获得第一个匹配:

$(this).parents("div").first().fadeOut();
Run Code Online (Sandbox Code Playgroud)

$(document).on("click", ".close", function() {
  $(this).parents("div").first().fadeOut();
});
Run Code Online (Sandbox Code Playgroud)
.feed {
  width: 200px;
  height: 200px;
  background: red;
  position: relative;
}
.close {
  position: absolute;
  top: 0;
  right: 0;
}
Run Code Online (Sandbox Code Playgroud)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="feed">
  <div class="close">
    X
  </div>
</div>
Run Code Online (Sandbox Code Playgroud)

或者,您也可以通过选择父元素然后使用.closest()like 来排除父级:

$(this).parent().closest("div").fadeOut();
Run Code Online (Sandbox Code Playgroud)

但是,选择最接近的.feed元素而不是任何 元素会更好div:

$(this).closest(".feed").fadeOut();
Run Code Online (Sandbox Code Playgroud)

$(document).on("click", ".close", function() {
  $(this).closest(".feed").fadeOut();
});
Run Code Online (Sandbox Code Playgroud)
.feed {
  width: 200px;
  height: 200px;
  background: red;
  position: relative;
}
.close {
  position: absolute;
  top: 0;
  right: 0;
}
Run Code Online (Sandbox Code Playgroud)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="feed">
  <div class="close">
    X
  </div>
</div>
Run Code Online (Sandbox Code Playgroud)