요소가 부모의 자식인지 확인
다음 코드가 있습니다.
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
</head>
<div id="hello">Hello <div>Child-Of-Hello</div></div>
<br />
<div id="goodbye">Goodbye <div>Child-Of-Goodbye</div></div>
<script type="text/javascript">
<!--
function fun(evt) {
var target = $(evt.target);
if ($('div#hello').parents(target).length) {
alert('Your clicked element is having div#hello as parent');
}
}
$(document).bind('click', fun);
-->
</script>
</html>
Child-Of-Hello
클릭 할 때만 $('div#hello').parents(target).length
> 0을 반환합니다.
그러나 어디서나 클릭 할 때마다 발생합니다.
내 코드에 문제가 있습니까?
다른 조상이 아닌 직접 부모에게만 관심이 있다면을 (를) 사용 parent()
하고와 같이 셀렉터에게 줄 수 있습니다 target.parent('div#hello')
.
예 : http://jsfiddle.net/6BX9n/
function fun(evt) {
var target = $(evt.target);
if (target.parent('div#hello').length) {
alert('Your clicked element is having div#hello as parent');
}
}
또는 일치하는 조상이 있는지 확인하려면을 사용하십시오 .parents()
.
예 : http://jsfiddle.net/6BX9n/1/
function fun(evt) {
var target = $(evt.target);
if (target.parents('div#hello').length) {
alert('Your clicked element is having div#hello as parent');
}
}
.has()
이 목적을 위해 설계된 것 같습니다. jQuery 객체를 반환하므로 다음 사항도 테스트해야합니다 .length
.
if ($('div#hello').has(target).length) {
alert('Target is a child of #hello');
}
특정 선택 기가없는 요소가 있고 다른 요소의 자손인지 여전히 확인하려는 경우 jQuery.contains ()
jQuery.contains (container, included)
설명 : DOM 요소가 다른 DOM 요소의 자손인지 확인하십시오.
부모 요소와 확인하려는 요소를 해당 함수에 전달하면 첫 번째 요소의 하위 요소 인 경우이를 반환합니다.
IE8 + 용 바닐라 1 라이너 :
parent !== child && parent.contains(child);
작동 방식은 다음과 같습니다.
function contains(parent, child) {
return parent !== child && parent.contains(child);
}
var parentEl = document.querySelector('#parent'),
childEl = document.querySelector('#child')
if (contains(parentEl, childEl)) {
document.querySelector('#result').innerText = 'I confirm, that child is within parent el';
}
if (!contains(childEl, parentEl)) {
document.querySelector('#result').innerText += ' and parent is not within child';
}
<div id="parent">
<div>
<table>
<tr>
<td><span id="child"></span></td>
</tr>
</table>
</div>
</div>
<div id="result"></div>
대신 .closest ()를 사용하여 종료되었습니다.
$(document).on("click", function (event) {
if($(event.target).closest(".CustomControllerMainDiv").length == 1)
alert('element is a child of the custom controller')
});
두 용어를 바꾸면 코드가 작동합니다.
if ($(target).parents('div#hello').length) {
당신은 아이와 부모가 잘못된 길을 갔다.
다른 답변 외에도이 덜 알려진 방법을 사용하여 특정 부모의 요소를 가져올 수 있습니다.
$('child', 'parent');
귀하의 경우에는
if ($(event.target, 'div#hello')[0]) console.log(`${event.target.tagName} is an offspring of div#hello`);
Note the use of commas between the child and parent and their separate quotation marks. If they were surrounded by the same quotes
$('child, parent');
you'd have an object containing both objects, regardless of whether they exist in their document trees.
참고URL : https://stackoverflow.com/questions/3753634/check-if-an-element-is-a-child-of-a-parent
'development' 카테고리의 다른 글
jQuery를 사용하여 클릭시 앵커 텍스트 / href를 얻는 방법은 무엇입니까? (0) | 2020.08.03 |
---|---|
Gradle에 작업 종속성을 나열하는 방법이 있습니까? (0) | 2020.08.03 |
SQL Server : 열에서 행으로 (0) | 2020.08.03 |
프로그래밍 방식으로 연락처에 대한 액세스 요청 (0) | 2020.08.03 |
잘못된 구성 : iOS 7 이전의 IB 문서 컴파일은 더 이상 지원되지 않습니다 (0) | 2020.08.03 |