检查元素是否是父元素的子元素 [英] Check if an element is a child of a parent
问题描述
我有以下代码。
<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>
我预计只有在 Hello-Of-Hello
被点击, $('div#hello')。parents(target)。length
将返回> 0.
I expect only when Child-Of-Hello
being clicked, $('div#hello').parents(target).length
will return >0.
然而,只要我点击任何地方就会发生。
However, it just happen whenever I click on anywhere.
我的代码有问题吗?
推荐答案
如果您只对直接父母而不是其他祖先感兴趣,您可以使用 parent()
,然后给它选择器,如 target.parent('div#hello')
。
If you are only interested in the direct parent, and not other ancestors, you can just use parent()
, and give it the selector, as in 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()
。
Or if you want to check to see if there are any ancestors that match, then use .parents()
.
示例: < a href =http://jsfiddle.net/6BX9n/1/ =noreferrer> 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');
}
}
这篇关于检查元素是否是父元素的子元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!