检测 DOM 树中定义的 id 是否存在

Detect if defined id in the DOM tree is present

我正在寻找一种方法来检测 JQuery 点击目标是否在他的 DOM 树中具有定义了 id $('#contextMenu') 的父级。

$("html").click(function(e) {
  if ($(e.target).parents('#contextMenu')) {
    alert('yes');
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul id="contextMenu">
  <li><a href="#"><i class="fa fa-user-plus"></i> share</a>
  </li>
</ul>

怎么做?

使用 .length 属性 检查元素是否存在。

$( "html" ).click(function(e) {         
   if ($(e.target).parents('#contextMenu').length) {
      alert('yes');
   }
});

如果长度为0表示没有找到元素,

检查 length 属性。

$( "html" ).click(function(e) {         
   if ($(e.target).parents('#contextMenu').length) {
      alert('yes');
   }
});

但是 .closest() 性能会更好。

感谢 @A. Wolff, You can use Event Delegation

$(document).on('click', '#contextMenu', function(){ 
   alert('yes'); 
});