我想检测到它是否内部有IMG。我的非工作代码是:
$("a").click(function() {
if ($( this ).has("img")) {
console.log("link has image inside it");
} else {
console.log("no image");
}
});
如果单击文本链接,.has((中有IMG的内容。我在这里缺少什么?
谢谢!
问题是因为has()
用于过滤jQuery对象。它不会返回布尔值。
要完成您需要的事情,您需要使用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>