最近的()方法无法按预期工作 [英] closest() method not working as expected

查看:37
本文介绍了最近的()方法无法按预期工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在下面有一个示例示例,我不确定为什么第一个示例(使用div)无法获得文本,而第二个示例(使用span)可以通过以下方式实现使用 closest() 的相同JS代码:

I've a sample example below, I'm not sure why the first example (using div's) didn't get the text when the second one (using span's) could achieve that with the same JS code using closest():

$('.class-1').closest('div').find('.class-2').text()


第一个代码段(使用div)无法使用closest()获取文本:


First snippet (using div's) cant get the text using closest():

console.log( $('.class-1').closest('div').find('.class-2').text() );

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
  <div class="class-1">Div 1 Content</div>
  <div class="class-2">Div 2 Content</div>
</div>

第二个代码段(使用span)使用closest()获取文本:

Second snippet (using span's) getting the text using closest():

console.log( $('.class-1').closest('div').find('.class-2').text() );

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
  <span class="class-1">Div 1 Content</span>
  <br/>
  <span class="class-2">Div 2 Content</span>
</div>

我知道在这种情况下可以返回class-2文本的替代方法parents()/parent()/siblings()/nextAll(),但是我只想知道这种行为会发生什么.

I know about the alternatives parents()/parent()/siblings()/nextAll() that can return the class-2 text in this case, but I want just to know what occur this behaviour.

推荐答案

因为 .closest() 检查调用元素是否也适合选择器,在您的情况下,.class-1也是div.

从文档中

说明:对于集合中的每个元素,获取第一个元素 通过测试元素本身并向上遍历来匹配选择器 通过它的祖先在DOM树中.

Description: For each element in the set, get the first element that matches the selector by testing the element itself and traversing up through its ancestors in the DOM tree.

这篇关于最近的()方法无法按预期工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆