> jQuery's.closest()
vs.parents()
:詳細的比較
在jQuery的.closest()
和.parents()
方法之間進行選擇,通常會取決於理解其主要差異。 本文闡明了它們的功能並提供了實踐示例。
方法
起點
搜索方向
返回值
Method | Starting Point | Search Direction | Return Value |
---|---|---|---|
.closest() |
Current element | Up the DOM tree | Zero or one element |
.parents() |
Parent element | Up the DOM tree | Zero or more elements (in reverse order) |
核心區別在於其起點。 .closest()
開始使用當前元素開始搜索,而.parents()
>從直接父開始。 兩者都穿過DOM樹向上穿越,但是.closest()
在第一個匹配的祖先停止,而.parents()
>繼續紮根,收集了所有匹配的祖先。
>使用示例:.parents()
元素:<li>
<code class="language-javascript">$('.btn.remove').on('click', _this.cache.$container, function(e) { e.preventDefault(); console.log('remove...'); $(this).parents('li').first().remove(); });</code>注意
的方法是必要的,因為.first()
可以返回多個元素。
.parents()
示例: .closest()
這更有效地實現了相同的結果:
<code class="language-javascript">$('.btn.remove').on('click', _this.cache.$container, function(e) { e.preventDefault(); console.log('remove...'); $(this).closest('li').remove(); });</code>直接返回第一個匹配的祖先,消除了對
的需求。 如在各種基準中所證明的那樣,這通常會提高性能。 .closest()
>
.first()
>
從當前元素進行搜索,停在第一次匹配項中; >從父母那裡搜索,返回所有匹配。 .closest()
>
.parents()
>最多返回一個; 可以返回多個。 .closest()
.parents()
沒有選擇器返回直接父。
.closest()
沒有匹配:<li>如果找不到匹配,則兩者都返回一個空的jQuery對象。
案例靈敏度:<li>選擇器對案例敏感。
>
鏈接:<li>>兩種方法都允許使用其他jQuery方法鏈接。總而言之,為了找到與特定選擇器匹配的最近祖先,
通常是其效率和清潔劑語法的首選。 當您需要與所有匹配的祖先元素一起工作時,>很有用。 選擇最適合您的特定需求和編碼樣式的方法。以上是使用jQuery&#x27; $ .closest()vs $ .parents()的詳細內容。更多資訊請關注PHP中文網其他相關文章!