2010-09-03 62 views
3

假設我在寫一個jQuery擴展方法。該方法應該爬一個元素的祖先樹,直到它到達文檔的根<html>標記,此時它應該停止。我實現了這個如下所示:jQuery:確定jQuery對象是否爲根html標記

$.fn.foo = function() { 

    var $foo = this; 

    while($foo[0] !== $(document).children()[0]) { 
     // do stuff with $foo 
     $foo = $foo.parent(); 
    } 

    // do stuff 

}; 

我的問題是:是否有比$foo[0] !== $(document).children()[0]更好的辦法知道是否我已經達到了根<html>標籤?

+0

該插件是否也應該使用''元素? – Anurag 2010-09-03 22:40:35

回答

3
$foo.is('html') 

你似乎是reimplementi ng parents(),但。

3

不要拿對第一個孩子,就看是否返回父:

var $foo = $(this); 

while($foo.parent().length > 0) { 
    // do stuff with $foo 
    $foo = $foo.parent(); 
} 

這裏有一個working fiddle

1

這是怎麼回事?

$.fn.foo = function() { 

    var $foo = this; 

    while($foo[0].tagName != 'HTML') { 
     // do stuff with $foo 
     $foo = $foo.parent(); 
    } 

    // do stuff 

}; 

或者,如果你實際上並不需要遍歷,但只希望做的事情,以給定節點的所有祖先,你可以使用。家長()像這樣:

$.fn.foo = function() { 

    var $foo = this; 

    $foo.parents().andSelf().each(function() { 
     // do stuff with $foo 
    }); 

    // do stuff 

}; 
相關問題