jquery event.target is_a_child_of(element)

匆匆过客 提交于 2020-01-11 00:09:09

问题


Given element, a variable containing a javascript object/DOM element, how do I determine if the event.target is an element inside element or not?

function(event){
   // assume that var element exists in this scope
   if(event.target == a_child_of(element))
      // do something
}


<div id="myDiv">
   <div class="innerDiv">
      <input type="text"/>
   </div>
</div>

If element is myDiv, an event occurring on the inner div or the input, or any other element that may exist inside myDiv should cause the statement to evaluate to true.

I imagine that I could use a recursive function to build an array of child elements and then check if the event.target is in the array, but I want to see if there's a simpler answer first.


回答1:


jQuery to the rescue:

if (jQuery.contains(element, e.target))



回答2:


You can also use .has()

if ($(element).has(e.target).length > 0){
//
}


来源:https://stackoverflow.com/questions/12222208/jquery-event-target-is-a-child-ofelement

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!