2011-04-06 3 views

답변

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 요소를 제공합니다. 합니다 (sonElement가 fatherElement 범위에있는 경우 검색)

2

이 작업을 시도 할 수 있습니다 :

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

멋집니다! 이것이 어떻게 작동하는지 조금 더 설명해 주시겠습니까? – wilsonpage

+0

다음 URL을 확인하십시오 : http://api.jquery.com/jQuery/#selector-context – Chandu

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

0

@ Harpyon의 답을 바탕으로 이것은 내 마지막 해결책이었다 :

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