jQuery click() 函数中的 .has() 显示错误结果

jQuery .has() inside click() function showing false result

我想检测点击的元素 (link) 中是否有 img。我的非工作代码是:

$("a").click(function() {
  if ($( this ).has("img")) {
    console.log("link has image inside it");
  } else {
    console.log("no image");
  }
});

如果您单击文本 link,.has()things 里面有 img。我在这里错过了什么?

谢谢!

问题是因为 has() 用于过滤 jQuery 对象;它不是 return 布尔值。

要执行您需要的操作,您需要使用 find()children(),具体取决于您要检查 img 元素的深度,然后 length,像这样:

$("a").click(function(e) {
  e.preventDefault(); // only for testing

  if ($(this).find("img").length) {
    console.log("link has image inside it");
  } else {
    console.log("no image");
  }
});
img { max-width: 300px; }
a { display: block; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<a href="https://google.com">
  <img src="https://upload.wikimedia.org/wikipedia/commons/3/3a/Cat03.jpg" alt="alt">
</a>

<a href="https://google.com">text link</a>