closest() 方法没有按预期工作
closest() method not working as expected
我在下面有一个示例,我不确定为什么第一个示例(使用 div
's)在第二个示例(使用 span
' s) 可以使用 closest()
:
使用相同的 JS 代码实现
$('.class-1').closest('div').find('.class-2').text()
第一个片段(使用 div
的)无法使用 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()
获取文本:
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>
我知道在这种情况下可以 return class-2
文本的替代方案 parents()/parent()/siblings()/nextAll()
,但我只想知道这种行为会发生什么。
因为 .closest()
检查调用元素是否也适合选择器,在您的情况下 .class-1
也是 div
.
来自文档:
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.
我在下面有一个示例,我不确定为什么第一个示例(使用 div
's)在第二个示例(使用 span
' s) 可以使用 closest()
:
$('.class-1').closest('div').find('.class-2').text()
第一个片段(使用 div
的)无法使用 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()
获取文本:
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>
我知道在这种情况下可以 return class-2
文本的替代方案 parents()/parent()/siblings()/nextAll()
,但我只想知道这种行为会发生什么。
因为 .closest()
检查调用元素是否也适合选择器,在您的情况下 .class-1
也是 div
.
来自文档:
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.