gpt4 book ai didi

javascript - Jquery 每个类元素并比较

转载 作者:行者123 更新时间:2023-11-30 09:31:25 25 4
gpt4 key购买 nike

我有一堆具有如下数据属性的图像:

<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 });
}
});

});

最佳答案

  1. 将属性选择器与 :not 选择器一起使用

attribute selector

Description: Selects elements that have the specified attribute, with any value.

:not selector

Description: Selects all elements that do not match the given 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>

关于javascript - Jquery 每个类元素并比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45978886/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com