1

Suppose I have this HTML structure:

<div id="Ancestor">
 <div>
   <div>
     ....
       <div class="DeepChild"></div>
...
<div id="NotAncestor">
 <div>
   <div>
     ....
       <div class="DeepChild"></div>

I want to know, when I click on a DeepChild div if it's a descendant of Ancestor.

Something like this:

$('.DeepChild').click(function () {
   if (whichcondition?? === true) { IsFromAncestor = true; }
});
4

3 回答 3

6
$(this).parents("#Ancestor").length > 0

如果您的父母身份类是静态的并且不会随着时间的推移而移动,您可能只想将侦听器附加到嵌套在其中的 div 和祖先:

$("#Ancestor .deepchild").click(...
于 2012-05-18T21:56:10.120 回答
3

这是一个老问题,已经有一个公认的答案,但我认为最好的选择还没有给出:

$(this).parents("#Ancestor").length > 0对于复杂的 DOM 结构可能会非常慢。

if ($('#Ancestor').find(this).length)
    //I'm under the  #Ancestor.

jsperf显示我的方式快三倍

于 2012-05-31T06:43:14.827 回答
0

这样的事情怎么样

$(this).parents("#Ancestor").length > 0
于 2012-05-18T21:57:03.523 回答