簡體   English   中英

jquery .closest()在嘗試訪問最近的上部div時選擇自己

[英]jquery .closest() select itself when trying to access the closest upper div

你好其實我想要的是隱藏div元素的直接上部div,如果它是空的

所以我寫了這樣的代碼

if ($.trim($('#searchQuery').html()) == '') {

    $('#searchQuery').closest("div").css("display", "none");
}

具有id searchQuery的元素本身就是div所以它正在做它隱藏自己。

有人知道在這種情況下該做什么,為什么它的行為是這樣的?

一些東西:

  • 使用.text()而不是.html()來避免獲取不會在修剪中刪除的HTML標記。
  • 使用.hide()代替.css("display", "none")
  • 使用.parent()表示直接父級。

示例解決方案

$('#searchQuery').parent().hide();

或者你可以使用:not(..)

$('#searchQuery').closest("div:not(#searchQuery)").hide();

http://api.jquery.com/not-selector/

它選擇自己因為它

從當前元素開始

http://api.jquery.com/closest/

或者你可以使用.parents(...) (注意結尾的s )。 它通過DOM樹傳播,直到找到您在參數中傳遞的選擇器。

http://api.jquery.com/parents/

請參閱Jquery .closest()文檔。

Jquery .closest()

對於集合中的每個元素,通過測試元素本身並遍歷DOM樹中的祖先來獲取與選擇器匹配的第一個元素。

1 .Begins with the current element

您的選擇器[.closest("div")]引用當前元素#searchQuery

2. Travels up the DOM tree until it finds a match for the supplied selector

#searchQuery是DOM樹中的第一個元素,它與當前的選擇器[.closest("div")]完美匹配[.closest("div")]

更新:

在這里,您可以使用.parent() .prev()選擇器而不是使用.closest()

或者你可以使用.closest()與選擇.not()選擇。

為什么不簡單呢?

$('#searchQuery').parent("div").css("display", "none");

順便說一下,正如trgraglia注意到的那樣,你也應該使用hide

$('#searchQuery').parent("div").hide();

取決於你的意思“上部div”

如果是以前的兄弟姐妹:

$('#searchQuery').prev().css("display", "none");

或者父母:

$('#searchQuery').parent().css("display", "none");

使用.parent()而不是最接近:)

這是一個老問題,但我今天遇到了同樣的問題並通過以下方式解決了這個問題:

$myelement.parent().closest('div');

這將忽略$ myelement並查看它

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM