Jquery每个类项和比较

时间:2017-08-31 10:13:14

标签: javascript jquery html css

我有一堆像这样的数据属性的图像:

<img class="overlay" data-filename="red" src="img1.png">
<img class="overlay" data-filename="yellow" src="img2.png">
<img data-filename="blue" src="img3.png">

因此我有这样的按钮:

<button class="lbtn" style="background-Color:red">
<button class="lbtn" style="background-Color:yellow">
<button class="lbtn" style="background-Color:blue">

如果我点击红色按钮,那些不包含数据文件名红色的图像的不透明度应为0。

到目前为止,我做到了这一点,但它无法正常工作:

$('.lbtn').click(function() {
 $(".overlay").each(function() {
     if($(this).data('filename') == $('.lbtn').attr('src') {
         $(this).css({ opacity: 0 });
     }
 });

});

3 个答案:

答案 0 :(得分:3)

  1. 使用属性选择器:not selector
  2. attribute selector

      

    描述:选择具有指定属性的元素,具有任何值。

    :not selector

      

    描述:选择与给定选择器不匹配的所有元素。

    $('.lbtn').click(function() {
      var color = $(this).attr('style').split(":")[1]
      console.log(color)
    
      $('img:not([data-filename=' + color + '])').css({
        opacity: 0
      });
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <img class="overlay" data-filename="red" src="img1.png">
    <img class="overlay" data-filename="yellow" src="img2.png">
    <img data-filename="blue" src="img3.png">
    
    
    <button class="lbtn" style="background-Color:red">Click</button>
    <button class="lbtn" style="background-Color:yellow">Click</button>
    <button class="lbtn" style="background-Color:blue">Click</button>

答案 1 :(得分:1)

要实现此目的,您可以向data元素添加button元素,该元素与data-filename上的img匹配。然后,您可以将其用于filter()它们并显示/隐藏相关的内容,如下所示:

$('.lbtn').click(function() {
  var filter = $(this).data('filter');
  var $imgs = $('.container img').hide();
  $imgs.filter('[data-filename="' + filter + '"]').show();
});
.red { background-color: #C00; }
.yellow { background-color: #CC0; }
.blue { background-color: #00C; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
  <img class="overlay" data-filename="red" src="img1.png" title="red">
  <img class="overlay" data-filename="yellow" src="img2.png" title="yellow">
  <img data-filename="blue" src="img3.png" title="blue">
</div>

<button class="lbtn red" data-filter="red">Red</button>
<button class="lbtn yellow" data-filter="yellow">Yellow</button>
<button class="lbtn blue" data-filter="blue">Blue</button>

答案 2 :(得分:0)

会稍微改变您的代码:

$('.lbtn').click(function() {
 var self= $(this);
 $(".overlay").each(function() {
     if($(this).data('filename') == $(self).attr('src') {
         $(this).css({ opacity: 0 });
     }
 });

var self = $(this); //这是触发事件的元素,你需要记住由于检查而导致的id。当您尝试检查$(&#39; .lbtn&#39;)。attr(&#39; src&#39;)时,它会占用所有三个按钮并且无法正常工作 AND按钮也需要具有属性src!