2011-04-06 79 views
0

好吧我有一個jQuery對象保存在一個變量中,我想測試它是否是另一個對象的父對象。那可能嗎?jQuery:如何使用父母()與jQuery對象作爲參數?

var fatherElement= $('#fatherElement'); 

if($('#sonElement').parents(fatherElement).length>0){ 
alert('Luke I AM your father!'); 
} 

你抓住我的漂移嗎? 愛這個律」問題的一些幫助:)

回答

3
if ($('#sonElement').parents("#fatherElement").length > 0) 
{ 
    alert('Luke I AM your father!'); 
} 

.partents需要selecor作爲參數。如果你只有一個變量的父母,你可以使用jQuery.contains

var fatherElement = $('#fatherElement').get(); 

if (jQuery.contains($('#sonElement').get(), fatherElement)) 
{ 
    alert('Luke I AM your father!'); 
} 

.get簡單地給我們的jQuery對象的DOM元素。

2

你可以試試這個(搜索如果sonElement在fatherElement範圍存在):

var fatherElement= $('#fatherElement'); 
if($('#sonElement', fatherElement).length>0){ 
    alert('Luke I AM your father!'); 
} 
+0

這看起來不錯!你能再解釋一下它是如何工作的嗎? – wilsonpage 2011-04-06 18:24:55

+0

檢查此URL:http://api.jquery.com/jQuery/#selector-context – Chandu 2011-04-06 18:28:06

1

我認爲這是你在找什麼:

$.fn.hasParent = function(objs) { 
    // ensure that objs is a jQuery array 
    objs = $(objs); var found = false; 
    $(this[0]).parents().andSelf().each(function() { 
     if ($.inArray(this, objs) != -1) { 
      found = true; 
      return false; // stops the each... 
     } 
    }); 
    return found; 
} 

參考:http://blog.bandit.co.nz/post/451104345/jquery-hasparent-function

+0

您可以稍後使用此功能,如下所示: '$('#sonElement')。hasParent($('#fatherElement') )' – keremkacel 2011-04-06 18:21:26

0

根據@ Harpyon的回答,這是我的最終解決方案:

var parent = $('#fatherElement')[0]; 
var child = $('#sonElement')[0]; 
alert($.contains(parent,child));//alerts 'true' or 'false'