我如何定位带有 jquery 的 href 的图像?

How can i target an image with an a href with jquery?

我正在尝试使用 jquery 在 href 图像上添加类别标签。现在我有以下 fiddle: https://jsfiddle.net/Eddiebouncer/43x6L2bj/ jquery 检查 link 中的类别并添加标签。但这也针对 text-links(最终是预期的)。

我如何才能只定位带有图像的 href 以覆盖标签?

问候,Ed'

HTML

<div style="padding:20px;margin-top:40px;">
  Example with 2 images with category A and B. Script generates a category-label accordingly.
</div>
<div class="relative-container">
  <a href="something/category-A/#"><img src="https://placehold.it/300x150" /></a>
</div>
<div class="relative-container">
  <a href="something/category-B/#"><img src="https://placehold.it/300x150" /></a>
</div>
<div style="padding:20px;">
  Here a text link - but this shouldn't be targeted: <a href="something/category-A/#">read more</a>
</div>

JS

$(document).ready(function() {
  $('a[href*="category-A"]').append('<div id="overlay-A">category A</div>');
  $('a[href*="category-B"]').append('<div id="overlay-B">category B</div>');
});

CSS

.relative-container {
  position: relative;
}

#overlay-A,
#overlay-B {
  display: inline block;
  position: absolute;
  top: 0;
  left: 0;
  padding: 12px;
  color: #fff;
}

#overlay-A {
  background: rgba(0, 0, 120, 0.75);
}

#overlay-B {
  background: rgba(0, 120, 0, 0.75);
}

很简单,用.relative-containerclass来区分两者

$(document).ready(function() {
  $('.relative-container a[href*="category-A"]').append('<div id="overlay-A">category A</div>');

  $('.relative-container a[href*="category-B"]').append('<div id="overlay-B">category B</div>');
});

或者测试 link 是否有图片

$('.relative-container a[href*="category-A"]').each(function() {
   if($(this).find('img').length) {
      $(this).append('<div id="overlay-B">category B</div>');
    }
})