bre*_*ine 14 jquery traversal jquery-traversing
我需要介于.closest()和之间的功能.parents().我将一些CSS应用于某个元素的所有父母,直到某个父母.现在我正在while循环,但似乎有更好的方法来做到这一点.
var goUp = $(".distant-child");
while(!goUp.hasClass("ancestor-to-stop-at")){
goUp.css("height","100%");
goUp = goUp.parent();
}
Run Code Online (Sandbox Code Playgroud)
我宁愿做其中一件事:
$(".distant-child").closest(".ancestor-to-stop-at").css("height","100%"); //won't work because .closest() only returns the top ancestor
$(".distant-child").parents(".ancestor-to-stop-at").css("height","100%"); //won't work because .parents() doesn't take this parameter and won't stop at the specified element.
Run Code Online (Sandbox Code Playgroud)
如何在没有while循环的情况下实现这一目标?
Sta*_*ble 24
您可以使用jquery parentsUntil()函数
$(".distant-child").parentsUntil(".ancestor-to-stop-at").css("height","100%");
Run Code Online (Sandbox Code Playgroud)