我需要应用这个小jquery函数:
$(function(){
$('.trigger').click(function(){
$('.img-popup').fadeIn(500);
$('.overlay').fadeIn(500);
});
$('.overlay').click(function(){
$('.img-popup').fadeOut(500);
$('.overlay').fadeOut(500);
});
});对一系列的divs:
<td class="result" >
<div class="trigger"><b>Show image 1</b></div>
<div class="overlay"></div>
<div class="img-popup">
<img src="imageurl-1">
</div>
</td>
...
<td class="result" >
<div class="trigger"><b>Show image 2</b></div>
<div class="overlay"></div>
<div class="img-popup">
<img src="imageurl-2">
</div>
</td>什么是最好的方法?
我觉得我应该在某个地方使用.each(),但是如何才能让.overlay类和相关的..img弹出显示相关的div呢?
或者我可以更改$('.trigger').click(function(),让它只使用最近的..img弹出div?
提前谢谢。
发布于 2015-04-20 20:40:43
您可以使用类似的内容来引用正确的img:
$(".trigger").click(function(){
$(this).siblings('.img-popup').fadeIn(500);
$(this).siblings('.overlay').fadeIn(500);
}
$(".overlay").click(function(){
$(this).siblings('.img-popup').fadeOut(500);
$(this).siblings('.overlay').fadeOut(500);
}发布于 2015-04-20 20:43:59
您不需要使用each()循环,只需使用$(this)作为单击按钮,使用父选择器和jQuery查找.img-popup和.overlay
$(function(){
$('.trigger').click(function(){
var element = $(this), parent = element.parent(".result"),
img_popup = parent.find('.img-popup'),
overlay = parent.find('.overlay');
img_popup.fadeIn(500);
overlay.fadeIn(500);
});
$('.overlay').click(function(){
var element = $(this), parent = element.parent(".result"),
img_popup = parent.find('.img-popup');
img_popup.fadeOut(500);
element.fadeOut(500);
});
});发布于 2015-04-20 20:44:06
对于给定的代码,您可以只使用siblings(),因此在单击处理程序中使用这些来实现目标
$(this).siblings('.img-popup');
$(this).siblings('.overlay');如果html变得更复杂,可以使用.closest()获取结果父级,如下所示
var $result = $(this).closest('.result');
$result.find('.img-popup');
$result.find('.overlay');https://stackoverflow.com/questions/29757888
复制相似问题