我正在尝试使用 .closest
来fadeOut
图像。要淡入淡出的图像有一个.icon
类,页面上有多个.icons
,所以我想使用this
和.closest
将 .icon
定位到与单击的元素相同的 div 内。
My JS Fiddle 显示了该功能。单击较小的方 block ,文本就会淡入。https://jsfiddle.net/x9sxcLr9/
但是,图标/大方 block 也应该随着文本淡入而淡出。这是该功能的代码:
$(this).closest("img.icon").fadeOut( "fast", function() {});
HTML 设置使用 .cross
作为事件处理程序,因此它应该找到附近正确的 .icon
(在同一个 div 中),但它没有好像找到了...
<div class="">
<img class="icon" src="http://placehold.it/100x100" />
<img class="cross" src="http://placehold.it/35x35" />
...
</div>
$( ".cross" ).click(function() { ... }
我哪里出错了?
最佳答案
您应该使用 sibling
而不是最接近的
。 Closest
将查找具有给定类的祖先。由于该元素是单击元素的同级元素,因此使用 siblings
。
$(".cross").click(function() {
var status = $(this).parent().attr("class")
if (status == 'active') {
$(this).parent(this).removeClass("active");
} else {
$(this).parent(this).addClass("active");
$(this).siblings("img.icon").fadeOut("fast", function() {});
}
});
关于jquery - 在 img 上使用 .closest 淡出图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30306294/