我如何使用带有jref的href定位图像?

问题描述 投票:0回答:1

我正在尝试使用jquery在href图像上添加类别标签。现在我有以下小提琴:https://jsfiddle.net/Eddiebouncer/43x6L2bj/jQuery检查链接中的类别并添加标签。但这也以文本链接为目标(这将在最后得到预期)。

如何仅定位带有图像的href来覆盖标签?

问候,爱德'

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);
}
jquery append label categories overlay
1个回答
0
投票

容易,使用.relative-container类来区分这两个

$(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>');
});

或测试链接是否有图像

$('.relative-container a[href*="category-A"]').each(function() {
   if($(this).has('img')) {
      $(this).append('<div id="overlay-B">category B</div>');
    }
})
© www.soinside.com 2019 - 2024. All rights reserved.