javascript jquery event.target is_a_child_of(element)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12222208/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 15:38:08  来源:igfitidea点击:

jquery event.target is_a_child_of(element)

javascriptjqueryjavascript-events

提问by Nick

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

给定element一个包含 javascript 对象/DOM 元素的变量,我如何确定 event.target 是否是内部元素element

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 elementis myDiv, an event occurring on the inner div or the input, or any other element that may exist inside myDivshould cause the statement to evaluate to true.

如果elementmyDiv,则发生在内部 div 或输入或内部可能存在的任何其他元素上的事件myDiv应导致语句评估为真。

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.

我想我可以使用递归函数来构建一个子元素数组,然后检查 event.target 是否在数组中,但我想先看看是否有更简单的答案。

回答by Musa

You can also use .has()

你也可以使用 .has()

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

回答by SLaks

jQuery to the rescue:

jQuery 来救援

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